MSP-8292 Up deps
This commit is contained in:
1 parent
3a66223a89
commit
5daaea50a1
186 files changed
+7092
-1579
No files matched your search
@@ -1,6 +1,6 @@
|
||||
module msp-admin-service
|
||||
|
||||
go 1.26
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
@@ -9,25 +9,25 @@ require (
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/txix-open/bgjob v1.6.0
|
||||
github.com/txix-open/isp-kit v1.71.2
|
||||
github.com/txix-open/isp-kit v1.74.0
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/sync v0.22.0
|
||||
google.golang.org/grpc v1.82.1
|
||||
google.golang.org/grpc v1.83.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/buger/jsonparser v1.2.0 // indirect
|
||||
github.com/buger/jsonparser v1.6.0 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/getsentry/sentry-go v0.47.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.9.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/getsentry/sentry-go v0.48.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.10.1 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
@@ -38,10 +38,10 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.19.0 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mailru/easyjson v0.9.2 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
@@ -49,15 +49,15 @@ require (
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/pressly/goose/v3 v3.27.2 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/pressly/goose/v3 v3.27.3 // indirect
|
||||
github.com/prometheus/client_golang v1.24.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.69.0 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // indirect
|
||||
github.com/txix-open/etp/v4 v4.1.1 // indirect
|
||||
github.com/txix-open/etp/v4 v4.1.3 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
@@ -71,14 +71,14 @@ require (
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -9,8 +9,8 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/buger/jsonparser v1.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g=
|
||||
github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/buger/jsonparser v1.6.0 h1:IHTgLjkgckOjAp8p0aYfXkv+cqC+zrzALg/JywnPjxY=
|
||||
github.com/buger/jsonparser v1.6.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
@@ -23,19 +23,19 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
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/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8=
|
||||
github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
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/getsentry/sentry-go v0.48.0 h1:FRZNr7Uk1C86ev1bSJmYlUkL9oyivQA6YOcdYfaaMmY=
|
||||
github.com/getsentry/sentry-go v0.48.0/go.mod h1:E5UkA5wp1qR2+MDydNYlVeUiNN2xEdjYMidkgf0Qoss=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.9.0 h1:a4HXLwueuTCtgF93VpUsl8Zd2nG1VH2SgNWDPVEBg5U=
|
||||
github.com/go-faker/faker/v4 v4.9.0/go.mod h1:u1dIRP5neLB6kTzgyVjdBOV5R1uP7BdxkcWk7tiKQXk=
|
||||
github.com/go-faker/faker/v4 v4.10.1 h1:mGH3y0X8AfrXsfgPsPuTkWBYIebomvdkWEN1uDLoFFg=
|
||||
github.com/go-faker/faker/v4 v4.10.1/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
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-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
@@ -74,8 +74,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
|
||||
github.com/klauspost/compress v1.19.0/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/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -86,14 +86,14 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
|
||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
@@ -116,26 +116,26 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8=
|
||||
github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM=
|
||||
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/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
|
||||
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
|
||||
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.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk=
|
||||
github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y=
|
||||
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.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.12.0 h1:V0v14Iqfs+MwHWihJt/nGS5Ulu0vw572b2Co3mwunkI=
|
||||
github.com/rabbitmq/amqp091-go v1.12.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
|
||||
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
|
||||
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
|
||||
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -153,12 +153,12 @@ github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgj
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/bgjob v1.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
|
||||
github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM=
|
||||
github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU=
|
||||
github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
|
||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.71.2 h1:QQ9642Bd1t/gWfnlS4uygVaBYyAhz5VtV3Q4bNwMKGw=
|
||||
github.com/txix-open/isp-kit v1.71.2/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74=
|
||||
github.com/txix-open/isp-kit v1.74.0 h1:Gi1X8Jnf9ppV4TXq4kMCBgBjJjqSKh57X8038I+tQFw=
|
||||
github.com/txix-open/isp-kit v1.74.0/go.mod h1:Kob233jk1j/Js7UmopJ5b7JpVZrpWbagEAjasgfqTdk=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
@@ -192,8 +192,8 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRk
|
||||
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/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/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
@@ -216,12 +216,12 @@ golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df h1:O3ig1i5WDDzsVzRp+cCdgelT9vXnlnOFdlEeFtL4HCc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
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/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 h1:ybvH/ZpOcpCrjtkb7oW/fdlzbEmRVeumw19SRQmNFKU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:HJ9MpJLeDSstBkx1LILTpd5f41ADSMZcTPypw02qEGw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 h1:mJiOtnGp0k/BcSgdu03G2NwnscCfCH+h2QKUBZr18KI=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
|
||||
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -232,11 +232,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
|
||||
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
|
||||
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
|
||||
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
|
||||
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
@@ -23,7 +23,7 @@ var version = "1.0.0"
|
||||
|
||||
//go:generate swag init -pd -ot json -eot json
|
||||
func main() {
|
||||
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport)
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
|
||||
+2
@@ -16,3 +16,5 @@ PROOF_*.md
|
||||
REQPROOF_*.md
|
||||
proof-ux-log.md
|
||||
PROOF_UNDER_MODELED_REQUIREMENTS_PROPOSAL.md
|
||||
fuzz_results/
|
||||
testdata/fuzz/
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
# Changelog
|
||||
|
||||
## [v1.6.0] — 2026-07-29
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
|
||||
|
||||
### New API — `Append`
|
||||
|
||||
```go
|
||||
// Append to an array without knowing its length
|
||||
data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
|
||||
```
|
||||
|
||||
- **`Append(data, value, keys...)`** — appends `value` to the end of the JSON array addressed by `keys`. Addresses the top-level value when `keys` is empty; auto-vivifies a missing keyed path as a single-element array. Returns `MalformedArrayError` when the addressed value is not an array. Traced to SYS-REQ-009, SYS-REQ-110.
|
||||
|
||||
### Known issues — all resolved (zero open)
|
||||
|
||||
- **KI-2 fixed** — `ParseInt("-")` now returns an error instead of `(0, nil)`. One-line sign-only guard in `bytes.go:parseInt` (after stripping the sign byte, an empty remainder returns `(0, false, false)`).
|
||||
- **KI-3 fixed** — `Set` with an array-index path component under an object parent (and vice-versa) now auto-coerces the container type instead of emitting malformed JSON. (Disposition already set to `fixed` in v1.5.x.)
|
||||
- **KI-4 fixed** — `Set` on a top-level array-index beyond length now appends at the array's end (matching nested-array behavior under SYS-REQ-110) instead of returning `KeyPathNotFoundError`. Also cleans up trailing commas in malformed arrays.
|
||||
|
||||
**Zero open known issues.** Every previously shipped known issue is now resolved and covered by ReqProof L3 Assurance.
|
||||
|
||||
---
|
||||
|
||||
## [v1.5.1] — 2026-07-28
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
|
||||
|
||||
### Performance — 6.1x large-payload speedup
|
||||
|
||||
- **Fix stringEnd unbounded backslash scan** — `stringEndConfig` was scanning the ENTIRE remaining parent document for backslashes (`bytes.IndexByte(data, '\\')`) instead of just the string body. On a 24kb large payload this walked tens of KB per string. Now bounded to `data[:firstQuote]` (the string body only). **128µs → 22µs (5.8x).**
|
||||
- **SWAR string scan** — replaced two separate `bytes.IndexByte` calls (quote + backslash) with a single inline 8-byte SWAR (SIMD-Within-A-Register) loop that checks for both characters simultaneously. **22µs → 21µs (additional 8%).**
|
||||
- **Benchmark suite updated** — all comparison libraries (gabs, easyjson, ffjson, etc.) updated to latest versions. Benchmark methodology documented (Apple M4 Max, Go 1.26.3, median of 5 runs). The `encoding/json` benchmark no longer uses ffjson-generated methods (the #126 ffjson measurement bug was fixed in v1.3.1).
|
||||
- **README benchmarks refreshed** — all numbers now reflect real measurements on modern hardware with current library versions.
|
||||
|
||||
### Updated benchmark results (Apple M4 Max, Go 1.26.3, median of 5 runs)
|
||||
|
||||
| Payload | jsonparser | encoding/json | easyjson | Speedup vs encoding/json |
|
||||
|---|---|---|---|---|
|
||||
| Small (190B, Get) | 382 ns | 1,335 ns | 312 ns | 3.5x |
|
||||
| Small (190B, EachKey) | 241 ns | — | — | 5.5x |
|
||||
| Medium (2.4kB, Get) | 3,894 ns | 10,564 ns | 2,444 ns | 2.7x |
|
||||
| Medium (2.4kB, EachKey) | 1,923 ns | — | — | 5.5x |
|
||||
| Large (24kB) | 20,788 ns | 134,123 ns | 32,765 ns | **6.4x** |
|
||||
|
||||
All jsonparser results: **0 bytes allocated, 0 allocations**.
|
||||
|
||||
---
|
||||
|
||||
## [v1.5.0] — 2026-07-28
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
|
||||
|
||||
v1.5.0 extends the formal-verification coverage to **123 requirements** (0 errors, 0 warnings) across all new APIs. Every new function is traced via source annotations, tested with MC/DC witnesses, and covered by the structure-aware fuzzer.
|
||||
|
||||
### Config struct — opt-in lenient parsing (#160, #115)
|
||||
|
||||
```go
|
||||
var Lenient = jsonparser.Config{AllowSingleQuotes: true, AllowUnknownEscapes: true}
|
||||
Lenient.Get(data, "key") // parses {'key':'value'} and unknown escapes
|
||||
```
|
||||
|
||||
- **`AllowSingleQuotes`** — accept `'key':'value'` alongside `"key":"value"` (JavaScript/Python-style). The same escape rules apply inside single-quoted strings.
|
||||
- **`AllowUnknownEscapes`** — pass through unknown escape sequences (`` \` ``, `\x`) literally instead of erroring.
|
||||
- The default Config is strict (RFC 8259 only). Package-level functions are unchanged.
|
||||
- Config methods mirror the full API: `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, `ObjectEach`.
|
||||
|
||||
### Streaming ReaderParser (#132, #257)
|
||||
|
||||
```go
|
||||
rp := jsonparser.NewReaderParser(file) // any io.Reader
|
||||
rp.Get("users", "[0]", "name") // path-based access from a stream
|
||||
```
|
||||
|
||||
- Path-based access to JSON data from an `io.Reader` — **no need to load the entire document into memory**.
|
||||
- Buffers data incrementally in 64KB chunks; memory is bounded by the largest value, not the document size.
|
||||
- Enables parsing **10GB+ JSON files** without OOM.
|
||||
- Methods: `Get`, `GetString`, `ArrayEach`.
|
||||
|
||||
### Name aliases (#66)
|
||||
|
||||
Canonical `EachXxx` pattern added alongside existing `XxxEach` names:
|
||||
|
||||
| New (canonical) | Old (kept for compat) |
|
||||
|---|---|
|
||||
| `EachArray` | `ArrayEach` |
|
||||
| `EachObject` | `ObjectEach` |
|
||||
| `EachArrayErr` | `ArrayEachErr` |
|
||||
| `EachArrayWildcard` | `ArrayEachWildcard` |
|
||||
|
||||
`EachKey`, `EachKeyErr`, `EachKeyWildcard` already matched the pattern. All old names remain functional.
|
||||
|
||||
### Proof
|
||||
|
||||
- 2 new SYS-REQs: 115 (Config/lenient parsing), 116 (streaming ReaderParser)
|
||||
- **123 requirements, 0 errors, 0 warnings, 279/279 functions traced**
|
||||
|
||||
---
|
||||
|
||||
## [v1.4.0] — 2026-07-28
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
|
||||
|
||||
v1.4.0 adds 9 new backward-compatible APIs, each traced to a formal requirement and verified with MC/DC coverage. **121 requirements, 0 errors, 0 warnings.**
|
||||
|
||||
### New APIs
|
||||
|
||||
**Iteration with error/break control** — resolves #53, #129, #176, #230, #255, #262
|
||||
- `ArrayEachErr` — callback returns `error` to stop early (`io.EOF` = graceful stop)
|
||||
- `EachKeyErr` — same pattern for EachKey
|
||||
|
||||
**Safe string handling** — resolves #144, #158, #218, #270
|
||||
- `Escape(s string) []byte` — RFC 8259 string escaping (inverse of `Unescape`)
|
||||
- `SetString(data, val, keys...)` — Set with auto-quoted value
|
||||
|
||||
**Container accessors** — resolves #175, #261, #271
|
||||
- `GetArrayLen` / `GetObjectLen` — count elements without a callback
|
||||
- `GetUint64` — uint64 variant of `GetInt`
|
||||
|
||||
**Delete found signal** — resolves #229
|
||||
- `DeleteFound(data, keys...) ([]byte, bool)` — returns whether the key was found
|
||||
|
||||
**Wildcard paths** — resolves #112
|
||||
- `EachKeyWildcard`, `ArrayEachWildcard`, `SetWildcard` — `[*]` path component
|
||||
|
||||
**JSONPath compiled paths** — resolves #234, #251
|
||||
- `ParsePath("$.users[0].name")` → `[]string` path
|
||||
- `CompilePath` + `CompiledPath` — pre-compile and reuse with Get/Set/Delete
|
||||
|
||||
### Fixes
|
||||
- EachKey no longer panics with >64 key components (#56)
|
||||
- Set pre-allocates output buffer, reducing allocations from 6 to 1 (#107)
|
||||
|
||||
### Proof
|
||||
- 3 new SYS-REQs: 112 (container length), 113 (wildcard paths), 114 (compiled paths)
|
||||
- **121 requirements, 384 MC/DC witness rows, 0 uncovered**
|
||||
|
||||
---
|
||||
|
||||
## [v1.3.1] — 2026-07-28
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance
|
||||
|
||||
v1.3.1 fixes 3 bugs that escaped the initial proof review, with new proof gates to prevent recurrence.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- **Fix Set/Delete input-buffer aliasing** (#209, #141) — `Set` and `Delete` no longer corrupt the caller's input `[]byte` when the slice has spare capacity. All mutation paths now allocate a fresh buffer.
|
||||
- **Fix EachKey array-index inconsistency** (#232) — `EachKey` now descends into terminal array-index paths consistently with `Get`.
|
||||
- **Fix benchmark measuring ffjson, not encoding/json** (#126) — benchmark payload types stripped of generated methods.
|
||||
|
||||
### Proof strengthening
|
||||
|
||||
| Bug | Proof gap | New gate |
|
||||
|---|---|---|
|
||||
| #209/#141 Set aliasing | No obligation said "Set must not mutate the input buffer" | New obligation `no_input_mutation` + `assertInputUnchanged` gate |
|
||||
| #232 EachKey ≠ Get | No cross-API consistency obligation | New obligation `api_consistency` + differential gate |
|
||||
| #126 benchmark ffjson | Proof didn't cover benchmarks | Benchmark honesty lint |
|
||||
|
||||
---
|
||||
|
||||
## [v1.3.0] — 2026-07-27
|
||||
|
||||
### Formally verified by [ReqProof](https://reqproof.com)
|
||||
|
||||
jsonparser v1.3.0 is the **first Go library proven to L3 assurance** by [ReqProof](https://reqproof.com), a git-native requirements-engineering and formal-verification platform. The entire codebase is now covered by:
|
||||
|
||||
- **118 formal requirements** (7 stakeholder + 111 system-level), each traced to code via source annotations and verified with FRETish formalization.
|
||||
- **100% Modified Condition/Decision Coverage (MC/DC)** — both code-level (every decision/condition branch exercised) and requirement-side (377/377 truth-table rows witnessed).
|
||||
- **A custom structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) generating grammar-valid mutations at 250k inputs/sec, plus path-mutation and `encoding/json` differential harnesses.
|
||||
- **L3 strict audit posture**: 0 errors, 0 warnings, all checks enabled.
|
||||
|
||||
The proof review found and fixed **7 real bugs** that years of community use, OSS-Fuzz, and standard fuzzing had missed. [Read the root-cause analysis →](docs/proof-gap-root-cause.md)
|
||||
|
||||
jsonparser serves as the **reference case study** for ReqProof — [learn more at reqproof.com](https://reqproof.com).
|
||||
|
||||
### Security / bug fixes
|
||||
|
||||
- **Fix Delete panic on malformed input with leading comma** (OSS-Fuzz 4649128545288192)
|
||||
`Delete` panicked with `index out of range [-1]` on inputs like `,{"test":1{}`.
|
||||
The `data[prevTok]` dereference is now guarded.
|
||||
|
||||
- **Fix empty-string key-component panics** (8 sites)
|
||||
`Get`, `GetString`, `GetInt`, `GetFloat`, `GetBoolean`, `GetUnsafeString`, `Set`,
|
||||
`Delete`, `EachKey` panicked with `index out of range [0]` when a key path contained
|
||||
an empty string (`""`). All 8 unguarded `keys[i][0]` dereference sites are now guarded
|
||||
with `len(...) > 0`. Found by the structure-aware hazard sweep.
|
||||
Reported by @c-tonneslan (#284).
|
||||
|
||||
- **Fix Set data loss on scalar arrays** (#267)
|
||||
`Set` on an array-index path beyond the current length silently overwrote the array
|
||||
instead of appending. `Set({"a":[1,2,3]}, 99, "a", "[9]")` now returns `{"a":[1,2,3,99]}`
|
||||
instead of `{"a":[99]}`. Reported by @Solaris-star (#286).
|
||||
|
||||
- **Fix Set malformed-JSON output on cross-type paths**
|
||||
`Set` with an array-index path component under an object parent (e.g. `Set({}, 9, "[5]")`)
|
||||
produced invalid JSON (`{[9]}`). Set now auto-coerces the container type to match the
|
||||
path, always producing valid JSON output.
|
||||
|
||||
- **Fix Delete trailing-comma malformation**
|
||||
`Delete` left a dangling trailing comma in the output when the deleted element was
|
||||
followed by JSON whitespace (space/tab/LF/CR) and a comma. Found by the structure-aware
|
||||
path-mutation fuzzer.
|
||||
|
||||
- **Fix ArrayEach spurious callback on non-array root**
|
||||
`ArrayEach` on a non-array root value (e.g. `ArrayEach({"a":1}, cb)`) invoked the
|
||||
callback with a spurious element before returning an error. The callback is no longer
|
||||
invoked; a clean error is returned immediately.
|
||||
|
||||
- **Fix lone-Unicode-surrogate mishandling in Unescape**
|
||||
`ParseString` on a string containing a lone high surrogate (e.g. `\uDB29` without a
|
||||
following low surrogate) synthesized a bogus non-BMP code point from the following
|
||||
literal bytes. Now substitutes U+FFFD (matching `encoding/json` behavior).
|
||||
|
||||
### Performance
|
||||
|
||||
- **parseInt fast-path for short numbers** — 22–37% faster on typical 1–10 digit integers.
|
||||
Numbers with ≤18 digits use direct int64 accumulation, bypassing the overflow-checked
|
||||
uint64 slow path. Contributed by @trevorprater (#285).
|
||||
|
||||
- **stringEnd SIMD fast path** — 12× faster on no-escape strings, 4.5× faster end-to-end
|
||||
on `Get` for string values. Uses `bytes.IndexByte` for the common case (no `\` before
|
||||
the closing `"`).
|
||||
|
||||
### Acknowledgments
|
||||
|
||||
- @c-tonneslan (#284) — reported the empty-string key-component panic
|
||||
- @Solaris-star (#286) — reported the Set array-index data-loss bug (#267)
|
||||
- @trevorprater (#285) — contributed the parseInt performance optimization
|
||||
- OSS-Fuzz (issue 4649128545288192) — the original Delete leading-comma panic
|
||||
- The [probelabs/json-fuzz](https://github.com/probelabs/json-fuzz) structure-aware fuzzer
|
||||
+4
-4
@@ -1,4 +1,7 @@
|
||||
FROM golang:1.6
|
||||
FROM golang:1.25
|
||||
|
||||
WORKDIR /go/src/github.com/buger/jsonparser
|
||||
ADD . /go/src/github.com/buger/jsonparser
|
||||
|
||||
RUN go get github.com/Jeffail/gabs
|
||||
RUN go get github.com/bitly/go-simplejson
|
||||
@@ -7,6 +10,3 @@ RUN go get github.com/antonholmquist/jason
|
||||
RUN go get github.com/mreiferson/go-ujson
|
||||
RUN go get -tags=unsafe -u github.com/ugorji/go/codec
|
||||
RUN go get github.com/mailru/easyjson
|
||||
|
||||
WORKDIR /go/src/github.com/buger/jsonparser
|
||||
ADD . /go/src/github.com/buger/jsonparser
|
||||
+11
@@ -26,6 +26,17 @@ profile:
|
||||
test:
|
||||
$(DRUN) go test $(LDFLAGS) ./ -run $(TEST) -timeout 10s $(ARGS) -v
|
||||
|
||||
# Full test suite including the heavy iteration-count suites that the standard
|
||||
# `proof audit` skips (property-based, reference-oracle, fuzz-harness coverage).
|
||||
# Run this in the dedicated CI fuzz job or locally before a release.
|
||||
test-full:
|
||||
go test ./... -count=1 -race -timeout 5m
|
||||
|
||||
# Structure-aware JSON fuzzer (grammar-based, far faster than generic
|
||||
# libFuzzer for finding parser-specific defects). See json_fuzz_test.go.
|
||||
fuzz-json:
|
||||
go test -run='^$$' -fuzz=FuzzJSONStructureAware -fuzztime=$(FUZZTIME) ./...
|
||||
|
||||
fmt:
|
||||
$(DRUN) go fmt ./...
|
||||
|
||||
|
||||
+149
-65
@@ -1,7 +1,26 @@
|
||||
[](https://goreportcard.com/report/github.com/buger/jsonparser) 
|
||||
[](https://goreportcard.com/report/github.com/buger/jsonparser) [](https://reqproof.com) 
|
||||
# Alternative JSON parser for Go (10x times faster standard library)
|
||||
|
||||
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **10 times faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
|
||||
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Formally Verified — the first Go library proven to L3 assurance by [ReqProof](https://reqproof.com)
|
||||
|
||||
jsonparser is the **reference case study** for [ReqProof](https://reqproof.com) — a git-native requirements-engineering and formal-verification platform. Every public API is traced to a formal requirement, every requirement is tested with **100% Modified Condition/Decision Coverage (MC/DC)**, and the entire parser is fuzzed by a custom **structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) that generates grammar-valid mutations at 250,000 inputs/second.
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Requirements traced | 118 (7 stakeholder + 111 system) |
|
||||
| Proof audit | **0 errors, 0 warnings** (L3 strict) |
|
||||
| Code-level MC/DC | **100% decisions, 100% conditions** |
|
||||
| Requirement-side MC/DC | **377/377 witness rows covered** |
|
||||
| Fuzz executions | 16M+ (structure-aware + path-mutation + encoding/json differential) |
|
||||
| Bugs found & fixed by the proof review | 7 (4 panics, 2 data-corruption, 1 encoding bug) |
|
||||
|
||||
The proof review caught bugs that years of community use, OSS-Fuzz, and standard fuzzing had missed — including a panic class across 8 unchecked-dereference sites, a silent data-loss bug in `Set`, and a malformed-output bug in `Delete`. [Read the full root-cause analysis →](docs/proof-gap-root-cause.md)
|
||||
|
||||
---
|
||||
|
||||
## Rationale
|
||||
Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex.
|
||||
@@ -55,16 +74,16 @@ if value, err := jsonparser.GetInt(data, "company", "size"); err == nil {
|
||||
size = value
|
||||
}
|
||||
|
||||
// You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN]
|
||||
jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
|
||||
// You can use `EachArray` helper to iterate items [item1, item2 .... itemN]
|
||||
jsonparser.EachArray(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
|
||||
fmt.Println(jsonparser.Get(value, "url"))
|
||||
}, "person", "avatars")
|
||||
|
||||
// Or use can access fields by index!
|
||||
jsonparser.GetString(data, "person", "avatars", "[0]", "url")
|
||||
|
||||
// You can use `ObjectEach` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
|
||||
jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
|
||||
// You can use `EachObject` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
|
||||
jsonparser.EachObject(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
|
||||
fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType)
|
||||
return nil
|
||||
}, "person", "name")
|
||||
@@ -90,6 +109,72 @@ jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, er
|
||||
// For more information see docs below
|
||||
```
|
||||
|
||||
## Lenient Parsing
|
||||
|
||||
The package-level functions remain strict RFC 8259 parsers. For inputs that use
|
||||
single-quoted strings or non-standard escapes, use a `Config` explicitly:
|
||||
|
||||
```go
|
||||
data := []byte(`{'name':'Ada','role':'engineer'}`)
|
||||
|
||||
name, err := jsonparser.Lenient.GetString(data, "name")
|
||||
// name == "Ada"
|
||||
```
|
||||
|
||||
`Lenient` enables both compatibility options. You can also enable only the
|
||||
extension your input requires:
|
||||
|
||||
```go
|
||||
config := jsonparser.Config{AllowUnknownEscapes: true}
|
||||
data := []byte("{\"path\":\"docs\\`draft\\x\"}")
|
||||
|
||||
path, err := config.GetString(data, "path")
|
||||
// path == "docs`draftx"
|
||||
```
|
||||
|
||||
The config-aware `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, and
|
||||
`ObjectEach` methods share the same signatures and behavior as their
|
||||
package-level counterparts apart from the enabled parsing extensions.
|
||||
`jsonparser.DefaultConfig` is strict; `jsonparser.Lenient` enables
|
||||
`AllowSingleQuotes` and `AllowUnknownEscapes`.
|
||||
|
||||
## Streaming
|
||||
|
||||
`ReaderParser` provides the same path-based lookup model for JSON read from an
|
||||
`io.Reader`, so a large document does not need to be loaded into a single byte
|
||||
slice:
|
||||
|
||||
```go
|
||||
file, err := os.Open("large.json")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
parser := jsonparser.NewReaderParser(file)
|
||||
name, err := parser.GetString("person", "name")
|
||||
```
|
||||
|
||||
To process a root array incrementally, use `ArrayEach`. Each callback value is
|
||||
valid for the duration of the callback; copy it if it must be retained:
|
||||
|
||||
```go
|
||||
parser := jsonparser.NewReaderParser(file)
|
||||
err := parser.ArrayEach(func(value []byte, valueType jsonparser.ValueType, err error) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
process(value, valueType)
|
||||
})
|
||||
```
|
||||
|
||||
The parser reads in 64 KiB chunks and discards completed prefixes. Its default
|
||||
sliding-window target is 64 MiB; customize it with
|
||||
`jsonparser.Config{MaxBufferSize: size}`. A single returned value or array
|
||||
element may exceed that target because its complete bytes are supplied to the
|
||||
caller. Create a new `ReaderParser` for each lookup or array traversal.
|
||||
`ReaderParser` also honors `AllowSingleQuotes` and `AllowUnknownEscapes`.
|
||||
|
||||
## Reference
|
||||
|
||||
Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it.
|
||||
@@ -146,15 +231,19 @@ func GetInt(data []byte, keys ...string) (val int64, err error)
|
||||
If you know the key type, you can use the helpers above.
|
||||
If key data type do not match, it will return error.
|
||||
|
||||
### **`ArrayEach`**
|
||||
### **`EachArray`**
|
||||
```go
|
||||
func ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
|
||||
func EachArray(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
|
||||
```
|
||||
Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`.
|
||||
`ArrayEach` remains available as a backward-compatible alias.
|
||||
The error-returning and wildcard variants follow the same naming convention:
|
||||
use `EachArrayErr` and `EachArrayWildcard`; `ArrayEachErr` and
|
||||
`ArrayEachWildcard` remain available for backward compatibility.
|
||||
|
||||
### **`ObjectEach`**
|
||||
### **`EachObject`**
|
||||
```go
|
||||
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
|
||||
func EachObject(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
|
||||
```
|
||||
Needed for iterating object, accepts a callback function. Example:
|
||||
```go
|
||||
@@ -162,8 +251,9 @@ var handler func([]byte, []byte, jsonparser.ValueType, int) error
|
||||
handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
|
||||
//do stuff here
|
||||
}
|
||||
jsonparser.ObjectEach(myJson, handler)
|
||||
jsonparser.EachObject(myJson, handler)
|
||||
```
|
||||
`ObjectEach` remains available as a backward-compatible alias.
|
||||
|
||||
|
||||
### **`EachKey`**
|
||||
@@ -224,6 +314,20 @@ Accepts multiple keys to specify path to JSON value (in case of updating or crea
|
||||
|
||||
Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avatars", "[0]", "url")`
|
||||
|
||||
### **`Append`**
|
||||
```go
|
||||
func Append(data []byte, value []byte, keys ...string) ([]byte, error)
|
||||
```
|
||||
Appends `value` to the end of the JSON array addressed by `keys`. When `keys` is
|
||||
empty, `Append` addresses the top-level value. If a keyed path does not exist,
|
||||
`Append` creates it as a single-element array using `Set`'s auto-vivification
|
||||
behavior. Returns `MalformedArrayError` if the addressed value is not an array.
|
||||
|
||||
```go
|
||||
// Append to an array without knowing its length
|
||||
data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
|
||||
```
|
||||
|
||||
|
||||
## What makes it so fast?
|
||||
* It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`.
|
||||
@@ -236,11 +340,12 @@ Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avat
|
||||
|
||||
There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
|
||||
For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
|
||||
Benchmarks run on standard Linode 1024 box.
|
||||
|
||||
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-28. The `encoding/json` benchmark types no longer carry ffjson-generated `UnmarshalJSON` methods (fixed in v1.3.1, issue #126), so these numbers reflect the real standard library, not generated code.
|
||||
|
||||
Compared libraries:
|
||||
* https://golang.org/pkg/encoding/json
|
||||
* https://github.com/Jeffail/gabs
|
||||
* https://github.com/Jeffail/gabs/v2
|
||||
* https://github.com/a8m/djson
|
||||
* https://github.com/bitly/go-simplejson
|
||||
* https://github.com/antonholmquist/jason
|
||||
@@ -251,42 +356,34 @@ Compared libraries:
|
||||
* https://github.com/buger/jsonparser
|
||||
|
||||
#### TLDR
|
||||
If you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`.
|
||||
`jsonparser` is up to 10 times faster than standard `encoding/json` package (depending on payload size and usage), and almost infinitely (literally) better in memory consumption because it operates with data on byte level, and provide direct slice pointers.
|
||||
`easyjson` wins in CPU in medium tests and frankly i'm impressed with this package: it is remarkable results considering that it is almost drop-in replacement for `encoding/json` (require some code generation).
|
||||
|
||||
It's hard to fully compare `jsonparser` and `easyjson` (or `ffson`), they a true parsers and fully process record, unlike `jsonparser` which parse only keys you specified.
|
||||
`jsonparser` is up to **6.4x faster** than standard `encoding/json` package (depending on payload size and usage), and **zero allocations** — it operates with data on byte level, and provide direct slice pointers. On large payloads, `jsonparser` is also faster than `easyjson` and `ffjson`.
|
||||
|
||||
If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choice. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.
|
||||
|
||||
`jsonparser` performance heavily depends on usage, and it works best when you do not need to process full record, only some keys. The more calls you need to make, the slower it will be, in contrast `easyjson` (or `ffjson`, `encoding/json`) parser record only 1 time, and then you can make as many calls as you want.
|
||||
|
||||
With great power comes great responsibility! :)
|
||||
|
||||
|
||||
#### Small payload
|
||||
|
||||
Each test processes 190 bytes of http log as a JSON record.
|
||||
It should read multiple fields.
|
||||
https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go
|
||||
|
||||
Library | time/op | bytes/op | allocs/op
|
||||
------ | ------- | -------- | -------
|
||||
encoding/json struct | 7879 | 880 | 18
|
||||
encoding/json interface{} | 8946 | 1521 | 38
|
||||
Jeffail/gabs | 10053 | 1649 | 46
|
||||
bitly/go-simplejson | 10128 | 2241 | 36
|
||||
antonholmquist/jason | 27152 | 7237 | 101
|
||||
github.com/ugorji/go/codec | 8806 | 2176 | 31
|
||||
mreiferson/go-ujson | **7008** | **1409** | 37
|
||||
a8m/djson | 3862 | 1249 | 30
|
||||
pquerna/ffjson | **3769** | **624** | **15**
|
||||
mailru/easyjson | **2002** | **192** | **9**
|
||||
buger/jsonparser | **1367** | **0** | **0**
|
||||
buger/jsonparser (EachKey API) | **809** | **0** | **0**
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------ | ------- | -------- | ------- |
|
||||
| encoding/json struct | 1335 | 415 | 9 |
|
||||
| encoding/json interface{} | 1441 | 1336 | 30 |
|
||||
| Jeffail/gabs | 1558 | 1464 | 38 |
|
||||
| bitly/go-simplejson | 1594 | 2120 | 34 |
|
||||
| github.com/ugorji/go/codec | 1286 | 1288 | 13 |
|
||||
| antonholmquist/jason | 4354 | 6816 | 105 |
|
||||
| mreiferson/go-ujson | 1031 | 1392 | 36 |
|
||||
| a8m/djson | 880 | 1160 | 25 |
|
||||
| pquerna/ffjson | **652** | **520** | **10** |
|
||||
| mailru/easyjson | **312** | **80** | **4** |
|
||||
| buger/jsonparser (ObjectEach) | **214** | 64 | 2 |
|
||||
| buger/jsonparser (EachKey) | **241** | **0** | **0** |
|
||||
| buger/jsonparser (Get) | **382** | **0** | **0** |
|
||||
|
||||
Winners are ffjson, easyjson and jsonparser, where jsonparser is up to 9.8x faster than encoding/json and 4.6x faster than ffjson, and slightly faster than easyjson.
|
||||
If you look at memory allocation, jsonparser has no rivals, as it makes no data copy and operates with raw []byte structures and pointers to it.
|
||||
`jsonparser` with `EachKey` is **5.5x faster** than `encoding/json` and **zero allocations**.
|
||||
|
||||
#### Medium payload
|
||||
|
||||
@@ -297,28 +394,17 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_paylo
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------- | ------- | -------- | --------- |
|
||||
| encoding/json struct | 57749 | 1336 | 29 |
|
||||
| encoding/json interface{} | 79297 | 10627 | 215 |
|
||||
| Jeffail/gabs | 83807 | 11202 | 235 |
|
||||
| bitly/go-simplejson | 88187 | 17187 | 220 |
|
||||
| antonholmquist/jason | 94099 | 19013 | 247 |
|
||||
| github.com/ugorji/go/codec | 114719 | 6712 | 152 |
|
||||
| mreiferson/go-ujson | **56972** | 11547 | 270 |
|
||||
| a8m/djson | 28525 | 10196 | 198 |
|
||||
| pquerna/ffjson | **20298** | **856** | **20** |
|
||||
| mailru/easyjson | **10512** | **336** | **12** |
|
||||
| buger/jsonparser | **15955** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey API) | **8916** | **0** | **0** |
|
||||
|
||||
The difference between ffjson and jsonparser in CPU usage is smaller, while the memory consumption difference is growing. On the other hand `easyjson` shows remarkable performance for medium payload.
|
||||
|
||||
`gabs`, `go-simplejson` and `jason` are based on encoding/json and map[string]interface{} and actually only helpers for unstructured JSON, their performance correlate with `encoding/json interface{}`, and they will skip next round.
|
||||
`go-ujson` while have its own parser, shows same performance as `encoding/json`, also skips next round. Same situation with `ugorji/go/codec`, but it showed unexpectedly bad performance for complex payloads.
|
||||
| encoding/json struct | 10564 | 616 | 18 |
|
||||
| pquerna/ffjson | 3962 | 736 | 15 |
|
||||
| mailru/easyjson | **2444** | **216** | **7** |
|
||||
| buger/jsonparser (Get) | **3894** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey) | **1923** | **0** | **0** |
|
||||
|
||||
`jsonparser` with `EachKey` beats `easyjson` on medium payload and remains zero-allocation.
|
||||
|
||||
#### Large payload
|
||||
|
||||
Each test processes a 24kb JSON record (based on Discourse API)
|
||||
Each test processes a 24kb JSON record (based on Discourse API).
|
||||
It should read 2 arrays, and for each item in array get a few fields.
|
||||
Basically it means processing a full JSON file.
|
||||
|
||||
@@ -326,16 +412,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payloa
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| --- | --- | --- | --- |
|
||||
| encoding/json struct | 748336 | 8272 | 307 |
|
||||
| encoding/json interface{} | 1224271 | 215425 | 3395 |
|
||||
| a8m/djson | 510082 | 213682 | 2845 |
|
||||
| pquerna/ffjson | **312271** | **7792** | **298** |
|
||||
| mailru/easyjson | **154186** | **6992** | **288** |
|
||||
| buger/jsonparser | **85308** | **0** | **0** |
|
||||
| encoding/json struct | 134123 | 4432 | 147 |
|
||||
| encoding/json interface{} | 176246 | 135824 | 2814 |
|
||||
| a8m/djson | 99295 | 135136 | 2679 |
|
||||
| pquerna/ffjson | 60129 | 4822 | 144 |
|
||||
| mailru/easyjson | 32765 | 4016 | 134 |
|
||||
| buger/jsonparser | **20788** | **0** | **0** |
|
||||
|
||||
`jsonparser` now is a winner, but do not forget that it is way more lightweight parser than `ffson` or `easyjson`, and they have to parser all the data, while `jsonparser` parse only what you need. All `ffjson`, `easysjon` and `jsonparser` have their own parsing code, and does not depend on `encoding/json` or `interface{}`, thats one of the reasons why they are so fast. `easyjson` also use a bit of `unsafe` package to reduce memory consuption (in theory it can lead to some unexpected GC issue, but i did not tested enough)
|
||||
|
||||
Also last benchmark did not included `EachKey` test, because in this particular case we need to read lot of Array values, and using `ArrayEach` is more efficient.
|
||||
`jsonparser` is the **fastest library overall** on large payloads: **6.4x faster than encoding/json**, **1.6x faster than easyjson**, and **zero allocations**.
|
||||
|
||||
## Formal Verification
|
||||
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package jsonparser
|
||||
|
||||
// SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083
|
||||
// EachArray is the canonical name; ArrayEach is kept for backward compatibility.
|
||||
func EachArray(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) {
|
||||
ArrayEach(data, cb, keys...)
|
||||
}
|
||||
|
||||
// SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084
|
||||
// EachObject is the canonical name; ObjectEach is kept for backward compatibility.
|
||||
func EachObject(data []byte, cb func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) error {
|
||||
return ObjectEach(data, cb, keys...)
|
||||
}
|
||||
|
||||
// SYS-REQ-004
|
||||
// EachArrayErr is the canonical name; ArrayEachErr is kept for backward compatibility.
|
||||
func EachArrayErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (int, error) {
|
||||
return ArrayEachErr(data, cb, keys...)
|
||||
}
|
||||
|
||||
// SYS-REQ-113
|
||||
// EachArrayWildcard is the canonical name; ArrayEachWildcard is kept for backward compatibility.
|
||||
func EachArrayWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) {
|
||||
return ArrayEachWildcard(data, cb, keys...)
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package jsonparser
|
||||
|
||||
// Append adds value to the end of the JSON array addressed by keys.
|
||||
//
|
||||
// When keys is empty, Append addresses the top-level value. If a keyed path
|
||||
// does not exist, Append creates it as a single-element array using Set's
|
||||
// auto-vivification behavior.
|
||||
//
|
||||
// SYS-REQ-009, SYS-REQ-110
|
||||
func Append(data []byte, value []byte, keys ...string) ([]byte, error) {
|
||||
_, dataType, startOffset, endOffset, err := internalGet(data, keys...)
|
||||
if err != nil {
|
||||
if err != KeyPathNotFoundError || len(keys) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
arrayValue := make([]byte, len(value)+2)
|
||||
offset := WriteToBuffer(arrayValue, "[")
|
||||
offset += copy(arrayValue[offset:], value)
|
||||
WriteToBuffer(arrayValue[offset:], "]")
|
||||
|
||||
return Set(data, arrayValue, keys...)
|
||||
}
|
||||
|
||||
if dataType != Array {
|
||||
return nil, MalformedArrayError
|
||||
}
|
||||
|
||||
closeOffset := endOffset - 1
|
||||
if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' {
|
||||
return nil, MalformedArrayError
|
||||
}
|
||||
|
||||
hasElements := nextToken(data[startOffset+1:closeOffset]) != -1
|
||||
extraSpace := len(value)
|
||||
if hasElements {
|
||||
extraSpace++
|
||||
}
|
||||
|
||||
result := make([]byte, len(data)+extraSpace)
|
||||
offset := copy(result, data[:closeOffset])
|
||||
if hasElements {
|
||||
offset += WriteToBuffer(result[offset:], ",")
|
||||
}
|
||||
offset += copy(result[offset:], value)
|
||||
copy(result[offset:], data[closeOffset:])
|
||||
|
||||
return result, nil
|
||||
}
|
||||
+25
-1
@@ -7,13 +7,37 @@ const maxUint64 = 1<<64 - 1
|
||||
|
||||
// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
|
||||
func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
|
||||
if len(bytes) == 0 {
|
||||
l := len(bytes)
|
||||
if l == 0 {
|
||||
return 0, false, false
|
||||
}
|
||||
|
||||
var neg bool = false
|
||||
i := 0
|
||||
if bytes[0] == '-' {
|
||||
neg = true
|
||||
i = 1
|
||||
}
|
||||
if i == l {
|
||||
return 0, false, false
|
||||
}
|
||||
|
||||
if l-i < 19 {
|
||||
for ; i < l; i++ {
|
||||
d := bytes[i] - '0'
|
||||
if d > 9 {
|
||||
return 0, false, false
|
||||
}
|
||||
v = 10*v + int64(d)
|
||||
}
|
||||
|
||||
if neg {
|
||||
return -v, true, false
|
||||
}
|
||||
return v, true, false
|
||||
}
|
||||
|
||||
if neg {
|
||||
bytes = bytes[1:]
|
||||
}
|
||||
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package jsonparser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Config controls opt-in parsing extensions. The zero value is strict and
|
||||
// accepts only RFC 8259 JSON strings and escapes.
|
||||
// SYS-REQ-115
|
||||
type Config struct {
|
||||
AllowSingleQuotes bool // #160: accept 'key':'value' alongside "key":"value"
|
||||
AllowUnknownEscapes bool // #115: accept unknown escape sequences instead of erroring
|
||||
MaxBufferSize int // ReaderParser sliding-window target; zero uses the 64 MiB default
|
||||
}
|
||||
|
||||
// DefaultConfig is the strict parser configuration used by package-level
|
||||
// functions.
|
||||
// SYS-REQ-115
|
||||
var DefaultConfig = Config{}
|
||||
|
||||
// Lenient accepts single-quoted strings and unknown escape sequences.
|
||||
// SYS-REQ-115
|
||||
var Lenient = Config{
|
||||
AllowSingleQuotes: true,
|
||||
AllowUnknownEscapes: true,
|
||||
}
|
||||
|
||||
// Get returns the value addressed by keys using c's parsing options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) Get(data []byte, keys ...string) ([]byte, ValueType, int, error) {
|
||||
value, dataType, _, endOffset, err := internalGetConfig(c, data, keys...)
|
||||
return value, dataType, endOffset, err
|
||||
}
|
||||
|
||||
// GetString returns the decoded string addressed by keys using c's parsing
|
||||
// options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) GetString(data []byte, keys ...string) (string, error) {
|
||||
value, dataType, _, err := c.Get(data, keys...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if dataType != String {
|
||||
if dataType == Null {
|
||||
return "", NullValueError
|
||||
}
|
||||
return "", fmt.Errorf("Value is not a string: %s", string(value))
|
||||
}
|
||||
|
||||
if bytes.IndexByte(value, '\\') == -1 {
|
||||
return string(value), nil
|
||||
}
|
||||
|
||||
var stackbuf [unescapeStackBufSize]byte
|
||||
unescaped, err := unescapeConfig(c, value, stackbuf[:])
|
||||
if err != nil {
|
||||
return "", MalformedValueError
|
||||
}
|
||||
return string(unescaped), nil
|
||||
}
|
||||
|
||||
// Set replaces the value addressed by keys using c's parsing options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) Set(data []byte, value []byte, keys ...string) ([]byte, error) {
|
||||
return setConfig(c, data, value, keys...)
|
||||
}
|
||||
|
||||
// Delete removes the value addressed by keys using c's parsing options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) Delete(data []byte, keys ...string) []byte {
|
||||
result, _ := deleteFoundConfig(c, data, keys...)
|
||||
return result
|
||||
}
|
||||
|
||||
// ArrayEach iterates over the addressed array using c's parsing options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) ArrayEach(data []byte, cb func([]byte, ValueType, int, error), keys ...string) (int, error) {
|
||||
return arrayEachConfig(c, data, cb, keys...)
|
||||
}
|
||||
|
||||
// ObjectEach iterates over the addressed object using c's parsing options.
|
||||
// SYS-REQ-115
|
||||
func (c Config) ObjectEach(data []byte, cb func([]byte, []byte, ValueType, int) error, keys ...string) error {
|
||||
return objectEachConfig(c, data, cb, keys...)
|
||||
}
|
||||
+171
-17
@@ -15,20 +15,62 @@ const lowSurrogateOffset = 0xDC00
|
||||
const basicMultilingualPlaneReservedOffset = 0xDFFF
|
||||
const basicMultilingualPlaneOffset = 0xFFFF
|
||||
|
||||
// NOTE: combineUTF16Surrogates is blocked by an unsupported `<<` shift op
|
||||
// in the translator (Phase T.* gap, beyond #1/#2/#5). Even though Fix #6
|
||||
// resolves the package-const references in this body, the shift remains
|
||||
// untranslated, so no lemma is attached here.
|
||||
func combineUTF16Surrogates(high, low rune) rune {
|
||||
return supplementalPlanesOffset + (high-highSurrogateOffset)<<10 + (low - lowSurrogateOffset)
|
||||
}
|
||||
|
||||
const badHex = -1
|
||||
|
||||
// reqproof:lemma h2I_range func(c byte) bool {
|
||||
// r := h2I(c)
|
||||
// return r == -1 || (r >= 0 && r <= 15)
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma h2I_decimal_digit func(c byte) bool {
|
||||
// if c < '0' || c > '9' { return true }
|
||||
// r := h2I(c)
|
||||
// return r >= 0 && r <= 9
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma h2I_uppercase_hex func(c byte) bool {
|
||||
// if c < 'A' || c > 'F' { return true }
|
||||
// r := h2I(c)
|
||||
// return r >= 10 && r <= 15
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma h2I_lowercase_hex func(c byte) bool {
|
||||
// if c < 'a' || c > 'f' { return true }
|
||||
// r := h2I(c)
|
||||
// return r >= 10 && r <= 15
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma h2I_nondigit_is_badhex func(c byte) bool {
|
||||
// if c >= '0' && c <= '9' { return true }
|
||||
// if c >= 'A' && c <= 'F' { return true }
|
||||
// if c >= 'a' && c <= 'f' { return true }
|
||||
// return h2I(c) == badHex
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma h2I_nonneg_implies_le_15 func(c byte) bool {
|
||||
// r := h2I(c)
|
||||
// if r >= 0 {
|
||||
// return r <= 15
|
||||
// }
|
||||
// return true
|
||||
// }
|
||||
func h2I(c byte) int {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return int(c - '0')
|
||||
case c >= 'A' && c <= 'F':
|
||||
return int(c - 'A' + 10)
|
||||
case c >= 'a' && c <= 'f':
|
||||
return int(c - 'a' + 10)
|
||||
if c >= 48 && c <= 57 { // '0'..'9'
|
||||
return int(c - 48)
|
||||
}
|
||||
if c >= 65 && c <= 70 { // 'A'..'F'
|
||||
return int(c-65) + 10
|
||||
}
|
||||
if c >= 97 && c <= 102 { // 'a'..'f'
|
||||
return int(c-97) + 10
|
||||
}
|
||||
return badHex
|
||||
}
|
||||
@@ -56,10 +98,28 @@ func decodeSingleUnicodeEscape(in []byte) (rune, bool) {
|
||||
// isUTF16EncodedRune checks if a rune is in the range for non-BMP characters,
|
||||
// which is used to describe UTF16 chars.
|
||||
// Source: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
|
||||
//
|
||||
// reqproof:lemma isUTF16EncodedRune_low_excluded func(r rune) bool {
|
||||
// return !(r < 0xD800) || !isUTF16EncodedRune(r)
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma isUTF16EncodedRune_const_high_bound func(r rune) bool {
|
||||
// // Fix #6: package-level const highSurrogateOffset (= 0xD800) now
|
||||
// // resolves at translation time. Below the high surrogate offset
|
||||
// // means definitely outside the UTF-16 surrogate range.
|
||||
// return !(r < highSurrogateOffset) || !isUTF16EncodedRune(r)
|
||||
// }
|
||||
//
|
||||
// reqproof:lemma isUTF16EncodedRune_const_bmp_bound func(r rune) bool {
|
||||
// // Fix #6: package-level const basicMultilingualPlaneReservedOffset (= 0xDFFF).
|
||||
// // Above the BMP-reserved offset means outside the UTF-16 surrogate range.
|
||||
// return !(r > basicMultilingualPlaneReservedOffset) || !isUTF16EncodedRune(r)
|
||||
// }
|
||||
func isUTF16EncodedRune(r rune) bool {
|
||||
return highSurrogateOffset <= r && r <= basicMultilingualPlaneReservedOffset
|
||||
return 0xD800 <= r && r <= 0xDFFF
|
||||
}
|
||||
|
||||
// SYS-REQ-115
|
||||
func decodeUnicodeEscape(in []byte) (rune, int) {
|
||||
if r, ok := decodeSingleUnicodeEscape(in); !ok {
|
||||
// Invalid Unicode escape
|
||||
@@ -71,12 +131,31 @@ func decodeUnicodeEscape(in []byte) (rune, int) {
|
||||
// tautological and has been removed — the real discriminator is whether r
|
||||
// falls in the UTF-16 surrogate range.
|
||||
return r, 6
|
||||
} else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { // Note: previous decodeSingleUnicodeEscape success guarantees at least 6 bytes remain
|
||||
// UTF16 "high surrogate" without manditory valid following Unicode escape for the "low surrogate"
|
||||
return utf8.RuneError, -1
|
||||
} else if r2 < lowSurrogateOffset {
|
||||
// Invalid UTF16 "low surrogate"
|
||||
} else if r >= lowSurrogateOffset {
|
||||
// Lone low surrogate (0xDC00-0xDFFF) with no preceding high surrogate.
|
||||
// Per RFC 8259/WHATWG a lone surrogate in a JSON string is malformed;
|
||||
// match encoding/json by substituting U+FFFD and consuming only the 6
|
||||
// bytes of this escape.
|
||||
return utf8.RuneError, 6
|
||||
} else if len(in) < 8 || in[6] != '\\' || in[7] != 'u' {
|
||||
// Lone high surrogate (0xD800-0xDBFF): the high-surrogate escape is not
|
||||
// followed by a "\u" low-surrogate escape. decodeSingleUnicodeEscape
|
||||
// assumes the \u prefix and reads hex at fixed offsets, so without this
|
||||
// guard it would misread whatever bytes follow (e.g. the literal "A7FA"
|
||||
// after "\uDB29") as a low surrogate and synthesize a bogus code point
|
||||
// (DEFECT-260727-SNGT). Substitute U+FFFD and consume only the 6 bytes
|
||||
// of the high surrogate, matching encoding/json.
|
||||
return utf8.RuneError, 6
|
||||
} else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok {
|
||||
// A "\u" follows the high surrogate but the low-surrogate escape is
|
||||
// itself malformed (truncated / bad hex) — the whole escape is broken.
|
||||
return utf8.RuneError, -1
|
||||
} else if r2 < lowSurrogateOffset || r2 > basicMultilingualPlaneReservedOffset {
|
||||
// The following "\uXXXX" is not a valid low surrogate (0xDC00-0xDFFF):
|
||||
// e.g. a BMP codepoint or another high surrogate. Treat the first escape
|
||||
// as a lone high surrogate → U+FFFD, consuming 6 bytes; the following
|
||||
// escape is reprocessed by the caller.
|
||||
return utf8.RuneError, 6
|
||||
} else {
|
||||
// Valid UTF16 surrogate pair
|
||||
return combineUTF16Surrogates(r, r2), 12
|
||||
@@ -99,6 +178,11 @@ var backslashCharEscapeTable = [...]byte{
|
||||
// how many characters were consumed from 'in' and emitted into 'out'.
|
||||
// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
|
||||
func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
|
||||
return unescapeToUTF8Config(DefaultConfig, in, out)
|
||||
}
|
||||
|
||||
// SYS-REQ-115
|
||||
func unescapeToUTF8Config(config Config, in, out []byte) (inLen int, outLen int) {
|
||||
if len(in) < 2 || in[0] != '\\' {
|
||||
// Invalid escape due to insufficient characters for any escape or no initial backslash
|
||||
return -1, -1
|
||||
@@ -110,6 +194,11 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
|
||||
// Valid basic 2-character escapes (use lookup table)
|
||||
out[0] = backslashCharEscapeTable[e]
|
||||
return 2, 1
|
||||
case '\'':
|
||||
if config.AllowSingleQuotes {
|
||||
out[0] = e
|
||||
return 2, 1
|
||||
}
|
||||
case 'u':
|
||||
// Unicode escape
|
||||
if r, inLen := decodeUnicodeEscape(in); inLen == -1 {
|
||||
@@ -122,17 +211,82 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
|
||||
}
|
||||
}
|
||||
|
||||
if config.AllowUnknownEscapes {
|
||||
// Lenient mode treats the escaped byte as a literal and discards the
|
||||
// escape marker. A trailing '\' and malformed \u escape remain errors:
|
||||
// they are truncated/invalid encodings, not unknown escape names.
|
||||
out[0] = in[1]
|
||||
return 2, 1
|
||||
}
|
||||
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
const lowerHex = "0123456789abcdef"
|
||||
|
||||
// Escape returns in as a JSON string literal, including the surrounding
|
||||
// quotation marks.
|
||||
// SYS-REQ-014
|
||||
func Escape(in string) []byte {
|
||||
var stackbuf [unescapeStackBufSize]byte
|
||||
out := stackbuf[:0]
|
||||
out = append(out, '"')
|
||||
|
||||
start := 0
|
||||
for i := 0; i < len(in); i++ {
|
||||
c := in[i]
|
||||
if c >= 0x20 && c != '"' && c != '\\' {
|
||||
continue
|
||||
}
|
||||
|
||||
out = append(out, in[start:i]...)
|
||||
switch c {
|
||||
case '"', '\\':
|
||||
out = append(out, '\\', c)
|
||||
case '\b':
|
||||
out = append(out, '\\', 'b')
|
||||
case '\f':
|
||||
out = append(out, '\\', 'f')
|
||||
case '\n':
|
||||
out = append(out, '\\', 'n')
|
||||
case '\r':
|
||||
out = append(out, '\\', 'r')
|
||||
case '\t':
|
||||
out = append(out, '\\', 't')
|
||||
default:
|
||||
out = append(out, '\\', 'u', '0', '0', lowerHex[c>>4], lowerHex[c&0x0f])
|
||||
}
|
||||
start = i + 1
|
||||
}
|
||||
|
||||
out = append(out, in[start:]...)
|
||||
return append(out, '"')
|
||||
}
|
||||
|
||||
// SetString replaces the value at keys with val encoded as a JSON string.
|
||||
// SYS-REQ-009
|
||||
func SetString(data []byte, val string, keys ...string) ([]byte, error) {
|
||||
return Set(data, Escape(val), keys...)
|
||||
}
|
||||
|
||||
// unescape unescapes the string contained in 'in' and returns it as a slice.
|
||||
// If 'in' contains no escaped characters:
|
||||
// Returns 'in'.
|
||||
//
|
||||
// Returns 'in'.
|
||||
//
|
||||
// Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)):
|
||||
// 'out' is used to build the unescaped string and is returned with no extra allocation
|
||||
//
|
||||
// 'out' is used to build the unescaped string and is returned with no extra allocation
|
||||
//
|
||||
// Else:
|
||||
// A new slice is allocated and returned.
|
||||
//
|
||||
// A new slice is allocated and returned.
|
||||
func Unescape(in, out []byte) ([]byte, error) {
|
||||
return unescapeConfig(DefaultConfig, in, out)
|
||||
}
|
||||
|
||||
// SYS-REQ-115
|
||||
func unescapeConfig(config Config, in, out []byte) ([]byte, error) {
|
||||
firstBackslash := bytes.IndexByte(in, '\\')
|
||||
if firstBackslash == -1 {
|
||||
return in, nil
|
||||
@@ -156,7 +310,7 @@ func Unescape(in, out []byte) ([]byte, error) {
|
||||
// leaves at least the backslash character in `in`.
|
||||
for {
|
||||
// Unescape the next escaped character
|
||||
inLen, bufLen := unescapeToUTF8(in, buf)
|
||||
inLen, bufLen := unescapeToUTF8Config(config, in, buf)
|
||||
if inLen == -1 {
|
||||
return nil, MalformedStringEscapeError
|
||||
}
|
||||
|
||||
+1262
-149
File diff suppressed because it is too large.
Load diff
+226
@@ -0,0 +1,226 @@
|
||||
package jsonparser
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
errEmptyPath = errors.New("jsonparser: path must not be empty")
|
||||
errMalformedPath = errors.New("jsonparser: malformed path")
|
||||
errUnterminatedKey = errors.New("jsonparser: unterminated quoted key")
|
||||
)
|
||||
|
||||
// ParsePath converts a JSONPath-style path into the path components accepted
|
||||
// by Get, Set, Delete, ArrayEach, and EachKey.
|
||||
// SYS-REQ-114
|
||||
func ParsePath(jsonPath string) ([]string, error) {
|
||||
if jsonPath == "" {
|
||||
return nil, errEmptyPath
|
||||
}
|
||||
|
||||
switch {
|
||||
case jsonPath == "$":
|
||||
return []string{}, nil
|
||||
case strings.HasPrefix(jsonPath, "$."):
|
||||
jsonPath = jsonPath[2:]
|
||||
case strings.HasPrefix(jsonPath, "$["):
|
||||
jsonPath = jsonPath[1:]
|
||||
case jsonPath[0] == '$':
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
|
||||
if jsonPath == "" {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
|
||||
// A path component is either a dot-delimited key or bracket notation.
|
||||
// Counting both separators gives an exact capacity for ordinary paths and
|
||||
// a safe upper bound for quoted keys containing dots or brackets.
|
||||
parts := make([]string, 0, 1+strings.Count(jsonPath, ".")+strings.Count(jsonPath, "["))
|
||||
|
||||
for pos := 0; pos < len(jsonPath); {
|
||||
switch jsonPath[pos] {
|
||||
case '.':
|
||||
return nil, errMalformedPath
|
||||
case '"':
|
||||
key, next, err := parseQuotedPathKey(jsonPath, pos)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts = append(parts, key)
|
||||
pos = next
|
||||
case '[':
|
||||
// A root array path or a bracket immediately following a dot has
|
||||
// no key component before its index.
|
||||
default:
|
||||
start := pos
|
||||
for pos < len(jsonPath) && jsonPath[pos] != '.' && jsonPath[pos] != '[' {
|
||||
if jsonPath[pos] == ']' || jsonPath[pos] == '"' {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
pos++
|
||||
}
|
||||
if start == pos {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
parts = append(parts, jsonPath[start:pos])
|
||||
}
|
||||
|
||||
for pos < len(jsonPath) && jsonPath[pos] == '[' {
|
||||
component, next, err := parseBracketPathComponent(jsonPath, pos)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts = append(parts, component)
|
||||
pos = next
|
||||
}
|
||||
|
||||
if pos == len(jsonPath) {
|
||||
break
|
||||
}
|
||||
if jsonPath[pos] != '.' {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
|
||||
pos++
|
||||
if pos == len(jsonPath) {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return nil, errMalformedPath
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// SYS-REQ-114
|
||||
func parseQuotedPathKey(path string, start int) (string, int, error) {
|
||||
contentStart := start + 1
|
||||
for pos := contentStart; pos < len(path); pos++ {
|
||||
switch path[pos] {
|
||||
case '\\':
|
||||
// Skip the escaped byte while locating the closing quote. Unescape
|
||||
// below performs complete JSON escape validation.
|
||||
pos++
|
||||
if pos >= len(path) {
|
||||
return "", 0, errUnterminatedKey
|
||||
}
|
||||
case '"':
|
||||
content := path[contentStart:pos]
|
||||
if strings.IndexByte(content, '\\') == -1 {
|
||||
return content, pos + 1, nil
|
||||
}
|
||||
|
||||
unescaped, err := Unescape([]byte(content), nil)
|
||||
if err != nil {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
return string(unescaped), pos + 1, nil
|
||||
default:
|
||||
if path[pos] < 0x20 {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "", 0, errUnterminatedKey
|
||||
}
|
||||
|
||||
// SYS-REQ-114
|
||||
func parseBracketPathComponent(path string, start int) (string, int, error) {
|
||||
end := start + 1
|
||||
for end < len(path) && path[end] != ']' {
|
||||
if path[end] == '[' || path[end] == '"' {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
end++
|
||||
}
|
||||
if end == len(path) || end == start+1 {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
|
||||
if path[start+1] == '*' {
|
||||
if end != start+2 {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
} else {
|
||||
for pos := start + 1; pos < end; pos++ {
|
||||
if path[pos] < '0' || path[pos] > '9' {
|
||||
return "", 0, errMalformedPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return path[start : end+1], end + 1, nil
|
||||
}
|
||||
|
||||
// CompiledPath stores a parsed path for repeated operations.
|
||||
// SYS-REQ-114
|
||||
type CompiledPath struct {
|
||||
parts []string
|
||||
}
|
||||
|
||||
// CompilePath parses jsonPath once for reuse.
|
||||
// SYS-REQ-114
|
||||
func CompilePath(jsonPath string) (CompiledPath, error) {
|
||||
parts, err := ParsePath(jsonPath)
|
||||
if err != nil {
|
||||
return CompiledPath{}, err
|
||||
}
|
||||
return CompiledPath{parts: parts}, nil
|
||||
}
|
||||
|
||||
// Get resolves the compiled path in data.
|
||||
// Verifies: SYS-REQ-001 (Get)
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) Get(data []byte) ([]byte, ValueType, int, error) {
|
||||
return Get(data, c.parts...)
|
||||
}
|
||||
|
||||
// GetString resolves the compiled path and returns its string value.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) GetString(data []byte) (string, error) {
|
||||
return GetString(data, c.parts...)
|
||||
}
|
||||
|
||||
// GetInt resolves the compiled path and returns its integer value.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) GetInt(data []byte) (int64, error) {
|
||||
return GetInt(data, c.parts...)
|
||||
}
|
||||
|
||||
// Set writes value at the compiled path.
|
||||
// Verifies: SYS-REQ-009 (Set)
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) Set(data []byte, value []byte) ([]byte, error) {
|
||||
return Set(data, value, c.parts...)
|
||||
}
|
||||
|
||||
// Delete removes the value at the compiled path.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) Delete(data []byte) []byte {
|
||||
return Delete(data, c.parts...)
|
||||
}
|
||||
|
||||
// ArrayEach iterates over the array at the compiled path.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) ArrayEach(data []byte, cb func([]byte, ValueType, int, error)) (int, error) {
|
||||
return ArrayEach(data, cb, c.parts...)
|
||||
}
|
||||
|
||||
// EachKey resolves the compiled path using EachKey.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) EachKey(data []byte, cb func(int, []byte, ValueType, error)) error {
|
||||
EachKey(data, cb, c.parts)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parts returns a copy of the compiled path components.
|
||||
// SYS-REQ-114
|
||||
func (c CompiledPath) Parts() []string {
|
||||
parts := make([]string, len(c.parts))
|
||||
copy(parts, c.parts)
|
||||
return parts
|
||||
}
|
||||
+164
-8
@@ -1,5 +1,10 @@
|
||||
project:
|
||||
name: jsonparser
|
||||
# High-assurance posture: the library is a pure function over untrusted,
|
||||
# adversarial byte input (fuzz targets, OSS-Fuzz). L3 is the strict
|
||||
# non-trivial level that obligates formalization, coverage, and hazard
|
||||
# review rather than informal inspection alone.
|
||||
assurance_target: L3
|
||||
specs:
|
||||
- path: specs/stakeholder
|
||||
prefix: STK-REQ
|
||||
@@ -32,14 +37,120 @@ project:
|
||||
- nil_safety
|
||||
- encoding_safety
|
||||
- edge_case
|
||||
- no_input_mutation
|
||||
- api_consistency
|
||||
- element_type_partition
|
||||
- non_array_root_no_callback
|
||||
commands:
|
||||
build: go build ./...
|
||||
test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
|
||||
# Standard audit test command: runs unit + MC/DC witness tests but
|
||||
# SKIPS the heavy iteration-count suites (property-based, reference-
|
||||
# oracle, fuzz-harness coverage) so `proof audit` stays fast on every
|
||||
# PR. Those suites run via `make test-full` (see Makefile) in the
|
||||
# dedicated CI "Fuzzing" job. Go's -skip flag (1.20+) accepts a regex;
|
||||
# Fuzz* functions only run under -fuzz anyway.
|
||||
test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
|
||||
# Named per-language test commands consumed by code_mcdc (the MC/DC
|
||||
# engine needs a discoverable go test command it can instrument and
|
||||
# rerun, then collect fingerprints). Mirrors the reqforge schema.
|
||||
tests:
|
||||
go:
|
||||
language: go
|
||||
command: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1
|
||||
# Instrumented execution path used only when the code-level
|
||||
# MC/DC engine reruns tests in its temp workspace (cwd =
|
||||
# <ws>/module). The engine does NOT inject -coverprofile or
|
||||
# -count into a user-provided command, so this must write the
|
||||
# managed cover artifact itself: ../cover.out resolves to the
|
||||
# workspace root the engine reads. -json is redirected back to
|
||||
# the source workspace via REQPROOF_MCDC_ORIGINAL_SOURCE_DIR so
|
||||
# test_results auto_link sees a fresh report. The ordinary
|
||||
# `command` above still feeds coverage_threshold / test_results
|
||||
# for the non-MC/DC path; -race still comes from test_args.
|
||||
mcdc_command: go test ./... -coverprofile=../cover.out -json > "$REQPROOF_MCDC_ORIGINAL_SOURCE_DIR/.proof/test-results/go-test.json" 2>&1
|
||||
# Fixtures are generated artifacts, not committed to the repo.
|
||||
# MC/DC coverage is enforced through test annotations instead.
|
||||
# To regenerate locally:
|
||||
# proof testgen specs/system parser --output tests/
|
||||
# proof proptest specs/system parser --source z3 --output tests/parser/
|
||||
#
|
||||
# Code signals — project-local OpenGrep rule packs.
|
||||
#
|
||||
# The jsonparser.boundary.unchecked-caller-slice-deref rule closes the
|
||||
# gap exposed by the 8th empty-key panic site (parser.go:1000): the
|
||||
# prior hazard sweep matched only `identifier[index][0]` and missed the
|
||||
# slice-expression variant `keys[depth:][0][0]`. The rule treats
|
||||
# slice-expression-then-index, direct-index-then-field, nested direct
|
||||
# index, computed-offset byte-slice index, and path-segment index as
|
||||
# the SAME hazard class, while excluding `len(X) > N && ...` /
|
||||
# `if len(X) > N { ... }` guarded sites and bounded `for i := range`
|
||||
# loops. Findings map to the boundary obligation class (already owned
|
||||
# by the parser requirement family) so each one opens a real review
|
||||
# item. The semantically precise class is panic_free_input_handling;
|
||||
# adopting it project-wide is the right follow-up — see the rule file
|
||||
# header for the migration note.
|
||||
#
|
||||
# Local dev / CI install of the analyzer backend:
|
||||
# npm install -g @opengrep/cli@1.22.0
|
||||
# `tools.opengrep.auto_download: true` below also fetches the pinned
|
||||
# version on the first `proof signals collect --provider opengrep`.
|
||||
signals:
|
||||
output_dir: proof/signals
|
||||
# Keep audit refresh explicit so a missing analyzer in CI does not
|
||||
# turn into a spurious red. Run `proof signals collect --provider
|
||||
# opengrep` before merge / locally to refresh findings; the audit
|
||||
# check consumes whatever cache that command writes.
|
||||
refresh_on_audit: false
|
||||
defaults: auto
|
||||
rule_packs:
|
||||
- proof/signals/rules/unchecked-caller-slice-deref.yaml
|
||||
providers:
|
||||
opengrep:
|
||||
enabled: true
|
||||
mode: run
|
||||
command:
|
||||
- opengrep
|
||||
- scan
|
||||
- '{configs}'
|
||||
- --sarif
|
||||
- --quiet
|
||||
- --no-rewrite-rule-ids
|
||||
- '{include_paths}'
|
||||
format: sarif
|
||||
include_paths:
|
||||
- parser.go
|
||||
- bytes.go
|
||||
- bytes_safe.go
|
||||
- bytes_unsafe.go
|
||||
- escape.go
|
||||
- fuzz.go
|
||||
exclude_paths:
|
||||
- '*_test.go'
|
||||
- benchmark/**
|
||||
# `go.parameter-boundary.degenerate` anchors the
|
||||
# parameter_boundary_safe catalog class, DEFINED as a
|
||||
# Solidity-style governance / operator setter whose value
|
||||
# is later consumed in slippage / throttle / timelock
|
||||
# arithmetic or truncated by a narrowing cast. This
|
||||
# project is a pure-function Go JSON parser library: the
|
||||
# only "setters" it exposes are top-level exported
|
||||
# functions taking byte slices, none consumed in
|
||||
# protection arithmetic and none cast to a narrower type.
|
||||
# The class's applies_when is never satisfied here, so
|
||||
# the project can neither satisfy nor violate it. The
|
||||
# honest record is "rule does not apply", not "83
|
||||
# requirement-owners each adjudicated and excused the
|
||||
# same site". Rule entries use the ProviderRuleID form
|
||||
# (hyphenated), matching how reqforge disables the same
|
||||
# rule for the same reason.
|
||||
disabled_rules:
|
||||
- go.parameter-boundary.degenerate
|
||||
fail_if_missing: false
|
||||
timeout_seconds: 120
|
||||
tools:
|
||||
opengrep:
|
||||
version: 1.22.0
|
||||
auto_download: true
|
||||
checks:
|
||||
solver_latency_clean:
|
||||
threshold: 360
|
||||
@@ -53,13 +164,14 @@ project:
|
||||
report_path: .proof/test-results/go-test.json
|
||||
slow_tests:
|
||||
enabled: true
|
||||
threshold_seconds: 60
|
||||
max_allowed: 5
|
||||
code_mcdc:
|
||||
severity: warn
|
||||
engine: go
|
||||
package_pattern: ./...
|
||||
coverpkg: ./...
|
||||
go_test_args:
|
||||
- -race
|
||||
languages:
|
||||
go:
|
||||
test_args:
|
||||
- -race
|
||||
min_decision_percent: 100
|
||||
min_condition_percent: 100
|
||||
max_incomplete_decisions: 0
|
||||
@@ -68,8 +180,6 @@ project:
|
||||
enabled: true
|
||||
language: go
|
||||
scope: ./...
|
||||
test_mcdc_annotations:
|
||||
enabled: true
|
||||
mcdc_coverage: {}
|
||||
proof_complexity_clean:
|
||||
max_formalized_requirements: 120
|
||||
@@ -80,6 +190,35 @@ project:
|
||||
A: 3
|
||||
B: 2
|
||||
C: 1
|
||||
# Worst-case-first hazard coverage gate (hazard-sweep role precondition).
|
||||
# `all` is stricter than proof's built-in default `security`: every
|
||||
# in-scope obligation class must carry an enumerated worst_case, so a
|
||||
# missing worst-case surfaces as a finding instead of a silent gap.
|
||||
hazard_consequence:
|
||||
require_worst_case_scope: all
|
||||
# Keep every remaining check enabled so the audit surface is fully
|
||||
# honest (no silently-disabled gates). Each was verified PASS on this
|
||||
# project; keeping them on catches regressions.
|
||||
change_evidence_complete:
|
||||
enabled: true
|
||||
code_signal_obligations_reviewed:
|
||||
enabled: true
|
||||
code_signal_unbindable:
|
||||
enabled: true
|
||||
description_grammar_enumeration_complete:
|
||||
enabled: true
|
||||
no_authored_change_surface_reviewed:
|
||||
enabled: true
|
||||
property_fixtures_exist:
|
||||
enabled: true
|
||||
flip_fixtures_exist:
|
||||
enabled: false
|
||||
fixture_staleness_clean:
|
||||
enabled: true
|
||||
signal_fixtures_valid:
|
||||
enabled: true
|
||||
property_based_test_coverage:
|
||||
enabled: true
|
||||
approval:
|
||||
required_for:
|
||||
assurance_levels:
|
||||
@@ -89,8 +228,25 @@ project:
|
||||
- system_owner
|
||||
- lead_engineer
|
||||
comment_required: true
|
||||
# Agent-driven review posture (mirrors reqforge self-dogfood): an AI
|
||||
# agent driving this repo may run `proof approve` at any assurance
|
||||
# level so the spec/hazard review loops can close autonomously. Set
|
||||
# `all: false` and enumerate levels to re-human-gate.
|
||||
agent_autonomous_for:
|
||||
all: true
|
||||
audit:
|
||||
# CI runs `proof audit --fail-level warn --scope full`; pinning the
|
||||
# same posture in config makes local runs match CI exactly.
|
||||
fail_level: warn
|
||||
scope: full
|
||||
invocation_log:
|
||||
enabled: true
|
||||
path: .proof/invocations.jsonl
|
||||
documentation:
|
||||
sources:
|
||||
- path: .
|
||||
type: auto
|
||||
threshold: 0
|
||||
verification_scope:
|
||||
exclude: null
|
||||
include: null
|
||||
+696
@@ -0,0 +1,696 @@
|
||||
package jsonparser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultReaderBufferSize = 64 * 1024
|
||||
defaultReaderMaxBufferSize = 64 * 1024 * 1024
|
||||
maxConsecutiveEmptyReads = 100
|
||||
)
|
||||
|
||||
// ReaderParser provides path-based access to a JSON stream. It is intended for
|
||||
// one operation per stream: call Get, GetString, or ArrayEach after creating
|
||||
// the parser. ReaderParser is not safe for concurrent use.
|
||||
//
|
||||
// The sliding window is bounded by Config.MaxBufferSize while skipping input.
|
||||
// A returned value (or one ArrayEach element) may exceed that size because its
|
||||
// complete byte slice must remain available to the caller.
|
||||
// SYS-REQ-116
|
||||
type ReaderParser struct {
|
||||
reader io.Reader
|
||||
buf []byte
|
||||
bufStart int64
|
||||
pos int
|
||||
config Config
|
||||
|
||||
readErr error
|
||||
emptyReads int
|
||||
}
|
||||
|
||||
// NewReaderParser creates a streaming parser. If opts contains a Config, the
|
||||
// first Config controls lenient parsing and the sliding-window size.
|
||||
// SYS-REQ-116
|
||||
func NewReaderParser(r io.Reader, opts ...Config) *ReaderParser {
|
||||
config := DefaultConfig
|
||||
if len(opts) > 0 {
|
||||
config = opts[0]
|
||||
}
|
||||
return &ReaderParser{
|
||||
reader: r,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns the value addressed by keys without loading the whole document.
|
||||
// As with the package-level Get, string values are returned without quotes but
|
||||
// retain their JSON escapes.
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) Get(keys ...string) (value []byte, vt ValueType, err error) {
|
||||
for _, key := range keys {
|
||||
if key == "" {
|
||||
return nil, NotExist, KeyPathNotFoundError
|
||||
}
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return nil, NotExist, KeyPathNotFoundError
|
||||
}
|
||||
return nil, NotExist, err
|
||||
}
|
||||
|
||||
var raw []byte
|
||||
if len(keys) == 0 {
|
||||
raw, err = rp.captureValue()
|
||||
} else {
|
||||
var found bool
|
||||
found, raw, err = rp.findValue(keys, 0)
|
||||
if err == nil && !found {
|
||||
err = KeyPathNotFoundError
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, NotExist, err
|
||||
}
|
||||
|
||||
value, vt, _, err = rp.config.Get(raw)
|
||||
if err != nil {
|
||||
return value, vt, err
|
||||
}
|
||||
return value, vt, nil
|
||||
}
|
||||
|
||||
// GetString returns and decodes the string addressed by keys.
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) GetString(keys ...string) (string, error) {
|
||||
value, vt, err := rp.Get(keys...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if vt != String {
|
||||
if vt == Null {
|
||||
return "", NullValueError
|
||||
}
|
||||
return "", valueTypeError("string", value)
|
||||
}
|
||||
if bytes.IndexByte(value, '\\') == -1 {
|
||||
return string(value), nil
|
||||
}
|
||||
|
||||
var stackbuf [unescapeStackBufSize]byte
|
||||
unescaped, err := unescapeConfig(rp.config, value, stackbuf[:])
|
||||
if err != nil {
|
||||
return "", MalformedValueError
|
||||
}
|
||||
return string(unescaped), nil
|
||||
}
|
||||
|
||||
// ArrayEach incrementally iterates a root JSON array. Callback value slices are
|
||||
// valid for the duration of the callback and must be copied if retained.
|
||||
// Memory use is bounded by the largest element plus the sliding read window.
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) ArrayEach(cb func(value []byte, vt ValueType, err error)) error {
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedObjectError
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b != '[' {
|
||||
return MalformedArrayError
|
||||
}
|
||||
rp.pos++
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedArrayError
|
||||
}
|
||||
return err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b == ']' {
|
||||
rp.pos++
|
||||
return nil
|
||||
}
|
||||
|
||||
for {
|
||||
raw, captureErr := rp.captureValue()
|
||||
if captureErr != nil {
|
||||
cb(nil, Unknown, captureErr)
|
||||
return captureErr
|
||||
}
|
||||
|
||||
value, vt, _, valueErr := rp.config.Get(raw)
|
||||
cb(value, vt, valueErr)
|
||||
if valueErr != nil {
|
||||
return valueErr
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedArrayError
|
||||
}
|
||||
return err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch b {
|
||||
case ']':
|
||||
rp.pos++
|
||||
return nil
|
||||
case ',':
|
||||
rp.pos++
|
||||
default:
|
||||
return MalformedArrayError
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedArrayError
|
||||
}
|
||||
return err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b == ']' {
|
||||
return MalformedArrayError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// findValue resolves keys[depth:] against the value at rp.pos. A not-found
|
||||
// result consumes the current value so a containing object can continue past a
|
||||
// duplicate key. A found result leaves the final value in the sliding buffer.
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) findValue(keys []string, depth int) (bool, []byte, error) {
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedJsonError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
if depth == len(keys) {
|
||||
raw, err := rp.captureValue()
|
||||
return err == nil, raw, err
|
||||
}
|
||||
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
switch b {
|
||||
case '{':
|
||||
return rp.findObjectValue(keys, depth)
|
||||
case '[':
|
||||
return rp.findArrayValue(keys, depth)
|
||||
default:
|
||||
if err := rp.skipValue(); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
return false, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) findObjectValue(keys []string, depth int) (bool, []byte, error) {
|
||||
rp.pos++ // opening {
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedObjectError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if b == '}' {
|
||||
rp.pos++
|
||||
return false, nil, nil
|
||||
}
|
||||
|
||||
for {
|
||||
matches, err := rp.readObjectKey(keys[depth])
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedJsonError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if b != ':' {
|
||||
return false, nil, MalformedJsonError
|
||||
}
|
||||
rp.pos++
|
||||
|
||||
if matches {
|
||||
found, raw, err := rp.findValue(keys, depth+1)
|
||||
if err != nil || found {
|
||||
return found, raw, err
|
||||
}
|
||||
} else {
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedJsonError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
if err := rp.skipValue(); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedObjectError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
switch b {
|
||||
case '}':
|
||||
rp.pos++
|
||||
return false, nil, nil
|
||||
case ',':
|
||||
rp.pos++
|
||||
default:
|
||||
return false, nil, MalformedObjectError
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedObjectError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if b == '}' {
|
||||
return false, nil, MalformedObjectError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) findArrayValue(keys []string, depth int) (bool, []byte, error) {
|
||||
wanted, ok := parseReaderArrayIndex(keys[depth])
|
||||
if !ok {
|
||||
if err := rp.skipValue(); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
return false, nil, nil
|
||||
}
|
||||
|
||||
rp.pos++ // opening [
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedArrayError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if b == ']' {
|
||||
rp.pos++
|
||||
return false, nil, nil
|
||||
}
|
||||
|
||||
for index := 0; ; index++ {
|
||||
if index == wanted {
|
||||
found, raw, err := rp.findValue(keys, depth+1)
|
||||
if err != nil || found {
|
||||
return found, raw, err
|
||||
}
|
||||
} else {
|
||||
if err := rp.skipValue(); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedArrayError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
switch b {
|
||||
case ']':
|
||||
rp.pos++
|
||||
return false, nil, nil
|
||||
case ',':
|
||||
rp.pos++
|
||||
default:
|
||||
return false, nil, MalformedArrayError
|
||||
}
|
||||
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return false, nil, MalformedArrayError
|
||||
}
|
||||
return false, nil, err
|
||||
}
|
||||
b, err = rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
if b == ']' {
|
||||
return false, nil, MalformedArrayError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func parseReaderArrayIndex(key string) (int, bool) {
|
||||
if len(key) < 3 || key[0] != '[' || key[len(key)-1] != ']' {
|
||||
return 0, false
|
||||
}
|
||||
index, err := strconv.Atoi(key[1 : len(key)-1])
|
||||
return index, err == nil && index >= 0
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) readObjectKey(wanted string) (bool, error) {
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if b != '"' && !(b == '\'' && rp.config.AllowSingleQuotes) {
|
||||
return false, MalformedJsonError
|
||||
}
|
||||
|
||||
// The parent prefix is no longer needed. Discarding it before retaining the
|
||||
// key ensures that an arbitrarily late key does not grow the window.
|
||||
rp.discardConsumed()
|
||||
start := rp.pos
|
||||
if err := rp.scanString(true); err != nil {
|
||||
return false, err
|
||||
}
|
||||
token := rp.buf[start:rp.pos]
|
||||
body := token[1 : len(token)-1]
|
||||
if bytes.IndexByte(body, '\\') == -1 {
|
||||
return string(body) == wanted, nil
|
||||
}
|
||||
|
||||
var stackbuf [unescapeStackBufSize]byte
|
||||
unescaped, err := unescapeConfig(rp.config, body, stackbuf[:])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return string(unescaped) == wanted, nil
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) captureValue() ([]byte, error) {
|
||||
if err := rp.skipWhitespace(); err != nil {
|
||||
if err == io.EOF {
|
||||
return nil, MalformedJsonError
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Retain only this value and any already-read suffix. The suffix is at most
|
||||
// one read chunk; prefixes consumed while locating the value are released.
|
||||
rp.discardConsumed()
|
||||
start := rp.pos
|
||||
if err := rp.scanValue(true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rp.buf[start:rp.pos], nil
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) skipValue() error {
|
||||
return rp.scanValue(false)
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) scanValue(retain bool) error {
|
||||
b, err := rp.peekByte(retain)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedJsonError
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
switch {
|
||||
case b == '"' || (b == '\'' && rp.config.AllowSingleQuotes):
|
||||
return rp.scanString(retain)
|
||||
case b == '[' || b == '{':
|
||||
return rp.scanComposite(retain, b)
|
||||
default:
|
||||
return rp.scanScalar(retain)
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) scanString(retain bool) error {
|
||||
quote, err := rp.peekByte(retain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rp.pos++
|
||||
escaped := false
|
||||
|
||||
for {
|
||||
b, err := rp.peekByte(retain)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return MalformedStringError
|
||||
}
|
||||
return err
|
||||
}
|
||||
rp.pos++
|
||||
|
||||
if escaped {
|
||||
escaped = false
|
||||
continue
|
||||
}
|
||||
if b == '\\' {
|
||||
escaped = true
|
||||
continue
|
||||
}
|
||||
if b == quote {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) scanComposite(retain bool, opening byte) error {
|
||||
stack := []byte{closingDelimiter(opening)}
|
||||
rp.pos++
|
||||
|
||||
for len(stack) > 0 {
|
||||
b, err := rp.peekByte(retain)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
if opening == '[' {
|
||||
return MalformedArrayError
|
||||
}
|
||||
return MalformedObjectError
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if b == '"' || (b == '\'' && rp.config.AllowSingleQuotes) {
|
||||
if err := rp.scanString(retain); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
switch b {
|
||||
case '{':
|
||||
stack = append(stack, '}')
|
||||
case '[':
|
||||
stack = append(stack, ']')
|
||||
case '}', ']':
|
||||
if b != stack[len(stack)-1] {
|
||||
return MalformedJsonError
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
rp.pos++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func closingDelimiter(opening byte) byte {
|
||||
if opening == '[' {
|
||||
return ']'
|
||||
}
|
||||
return '}'
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) scanScalar(retain bool) error {
|
||||
consumed := false
|
||||
for {
|
||||
b, err := rp.peekByte(retain)
|
||||
if err != nil {
|
||||
if err == io.EOF && consumed {
|
||||
return nil
|
||||
}
|
||||
if err == io.EOF {
|
||||
return MalformedJsonError
|
||||
}
|
||||
return err
|
||||
}
|
||||
if isReaderValueDelimiter(b) {
|
||||
if !consumed {
|
||||
return MalformedJsonError
|
||||
}
|
||||
return nil
|
||||
}
|
||||
consumed = true
|
||||
rp.pos++
|
||||
}
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func isReaderValueDelimiter(b byte) bool {
|
||||
return isJSONWhitespace(b) || b == ',' || b == '}' || b == ']'
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) skipWhitespace() error {
|
||||
for {
|
||||
b, err := rp.peekByte(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isJSONWhitespace(b) {
|
||||
return nil
|
||||
}
|
||||
rp.pos++
|
||||
}
|
||||
}
|
||||
|
||||
// peekByte returns the next byte. When retain is false, fully consumed chunks
|
||||
// are discarded before reading more data.
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) peekByte(retain bool) (byte, error) {
|
||||
for rp.pos >= len(rp.buf) {
|
||||
if !retain {
|
||||
rp.discardConsumed()
|
||||
}
|
||||
if err := rp.readMore(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return rp.buf[rp.pos], nil
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) readMore() error {
|
||||
if rp.readErr != nil {
|
||||
return rp.readErr
|
||||
}
|
||||
if rp.reader == nil {
|
||||
rp.readErr = io.EOF
|
||||
return rp.readErr
|
||||
}
|
||||
|
||||
readSize := defaultReaderBufferSize
|
||||
maxBufferSize := rp.config.MaxBufferSize
|
||||
if maxBufferSize <= 0 {
|
||||
maxBufferSize = defaultReaderMaxBufferSize
|
||||
}
|
||||
if readSize > maxBufferSize {
|
||||
readSize = maxBufferSize
|
||||
}
|
||||
if readSize < 1 {
|
||||
readSize = 1
|
||||
}
|
||||
|
||||
oldLen := len(rp.buf)
|
||||
if cap(rp.buf)-oldLen < readSize {
|
||||
grown := make([]byte, oldLen, oldLen+readSize)
|
||||
copy(grown, rp.buf)
|
||||
rp.buf = grown
|
||||
}
|
||||
rp.buf = rp.buf[:oldLen+readSize]
|
||||
n, err := rp.reader.Read(rp.buf[oldLen:])
|
||||
rp.buf = rp.buf[:oldLen+n]
|
||||
|
||||
if n > 0 {
|
||||
rp.emptyReads = 0
|
||||
if err != nil {
|
||||
rp.readErr = err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
rp.readErr = err
|
||||
return err
|
||||
}
|
||||
|
||||
rp.emptyReads++
|
||||
if rp.emptyReads >= maxConsecutiveEmptyReads {
|
||||
rp.readErr = io.ErrNoProgress
|
||||
return rp.readErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (rp *ReaderParser) discardConsumed() {
|
||||
if rp.pos == 0 {
|
||||
return
|
||||
}
|
||||
rp.bufStart += int64(rp.pos)
|
||||
rp.buf = rp.buf[rp.pos:]
|
||||
rp.pos = 0
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func valueTypeError(want string, value []byte) error {
|
||||
return &readerTypeError{want: want, value: string(value)}
|
||||
}
|
||||
|
||||
type readerTypeError struct {
|
||||
want string
|
||||
value string
|
||||
}
|
||||
|
||||
// SYS-REQ-116
|
||||
func (e *readerTypeError) Error() string {
|
||||
return "Value is not a " + e.want + ": " + e.value
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#!/bin/bash
|
||||
set -u
|
||||
cd "$(dirname "$0")"
|
||||
mkdir -p fuzz_results/crashes
|
||||
LOG=fuzz_results/campaign.log
|
||||
: > "$LOG"
|
||||
|
||||
TARGETS=(
|
||||
DeleteNative
|
||||
ParseStringNative
|
||||
EachKeyNative
|
||||
SetNative
|
||||
ObjectEachNative
|
||||
ParseFloatNative
|
||||
ParseIntNative
|
||||
ParseBoolNative
|
||||
TokenStartNative
|
||||
GetStringNative
|
||||
GetFloatNative
|
||||
GetIntNative
|
||||
GetBooleanNative
|
||||
GetUnsafeStringNative
|
||||
)
|
||||
PER_TARGET=${PER_TARGET:-180s}
|
||||
MAX_PASSES=${MAX_PASSES:-4}
|
||||
|
||||
count_crashes() { ls fuzz_results/crashes/ 2>/dev/null | wc -l | tr -d ' '; }
|
||||
|
||||
prev_count=$(count_crashes)
|
||||
pass=0
|
||||
while [ $pass -lt $MAX_PASSES ]; do
|
||||
pass=$((pass+1))
|
||||
echo "=== $(date '+%H:%M:%S') PASS $pass start (per-target=$PER_TARGET, baseline_unique_crashes=$prev_count) ===" | tee -a "$LOG"
|
||||
for t in "${TARGETS[@]}"; do
|
||||
pre=$(count_crashes)
|
||||
echo " -> $(date '+%H:%M:%S') Fuzz${t}" | tee -a "$LOG"
|
||||
go test -run='^$' -fuzz="^Fuzz${t}$" -fuzztime="${PER_TARGET}" \
|
||||
> "fuzz_results/${t}_pass${pass}.log" 2>&1
|
||||
rc=$?
|
||||
post=$(count_crashes)
|
||||
delta=$((post - pre))
|
||||
summary=$(tail -n 3 "fuzz_results/${t}_pass${pass}.log" | tr '\n' ' | ')
|
||||
echo " rc=$rc new_crashes=$delta total=$post :: $summary" | tee -a "$LOG"
|
||||
done
|
||||
new_count=$(count_crashes)
|
||||
pass_delta=$((new_count - prev_count))
|
||||
echo "=== $(date '+%H:%M:%S') PASS $pass done: total_unique_crashes=$new_count (+$pass_delta this pass) ===" | tee -a "$LOG"
|
||||
if [ $pass_delta -eq 0 ] && [ $pass -ge 2 ]; then
|
||||
echo "=== SATURATED after pass $pass — no new crashes ===" | tee -a "$LOG"
|
||||
break
|
||||
fi
|
||||
prev_count=$new_count
|
||||
done
|
||||
echo "=== $(date '+%H:%M:%S') CAMPAIGN COMPLETE total_unique_crashes=$(count_crashes) ===" | tee -a "$LOG"
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package jsonparser
|
||||
|
||||
import "strconv"
|
||||
|
||||
const wildcardPathComponent = "[*]"
|
||||
|
||||
// EachKeyWildcard resolves a path that may contain [*] components. A wildcard
|
||||
// requires an array at that position and fans out over its elements before
|
||||
// resolving the rest of the path. Multiple wildcards produce one callback for
|
||||
// every matching combination, in document order.
|
||||
//
|
||||
// idx is the zero-based order in which matches are reported.
|
||||
//
|
||||
// SYS-REQ-113
|
||||
func EachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), path ...string) error {
|
||||
nextMatch := 0
|
||||
return eachKeyWildcard(data, cb, &nextMatch, path)
|
||||
}
|
||||
|
||||
// SYS-REQ-113
|
||||
func eachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), nextMatch *int, path []string) error {
|
||||
wildcard := wildcardIndex(path)
|
||||
if wildcard == -1 {
|
||||
value, valueType, _, err := Get(data, path...)
|
||||
if err != nil {
|
||||
// A missing path has no value to report. Parsing errors for a
|
||||
// located terminal value, however, follow EachKey's convention
|
||||
// and are delivered to the callback as well as returned.
|
||||
if err != KeyPathNotFoundError {
|
||||
cb(*nextMatch, value, valueType, err)
|
||||
(*nextMatch)++
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
cb(*nextMatch, value, valueType, nil)
|
||||
(*nextMatch)++
|
||||
return nil
|
||||
}
|
||||
|
||||
array, valueType, _, err := Get(data, path[:wildcard]...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if valueType != Array {
|
||||
return MalformedArrayError
|
||||
}
|
||||
|
||||
remaining := path[wildcard+1:]
|
||||
_, err = ArrayEachErr(array, func(value []byte, elementType ValueType, _ int, parseErr error) error {
|
||||
if parseErr != nil {
|
||||
cb(*nextMatch, value, elementType, parseErr)
|
||||
(*nextMatch)++
|
||||
return parseErr
|
||||
}
|
||||
|
||||
if len(remaining) == 0 {
|
||||
cb(*nextMatch, value, elementType, nil)
|
||||
(*nextMatch)++
|
||||
return nil
|
||||
}
|
||||
|
||||
return eachKeyWildcard(value, cb, nextMatch, remaining)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// ArrayEachWildcard iterates over an array addressed by keys. A terminal [*]
|
||||
// component is accepted as an explicit request for all elements; without it,
|
||||
// the function behaves like ArrayEachErr.
|
||||
// SYS-REQ-113
|
||||
func ArrayEachWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) {
|
||||
if len(keys) > 0 && keys[len(keys)-1] == wildcardPathComponent {
|
||||
keys = keys[:len(keys)-1]
|
||||
}
|
||||
|
||||
index := 0
|
||||
return ArrayEachErr(data, func(value []byte, valueType ValueType, offset int, err error) error {
|
||||
current := index
|
||||
index++
|
||||
return cb(current, value, valueType, offset, err)
|
||||
}, keys...)
|
||||
}
|
||||
|
||||
// SetWildcard applies Set to every concrete path matched by [*]. Wildcards
|
||||
// may appear at any array position and may be repeated. If a wildcard matches
|
||||
// an empty array, data is returned unchanged.
|
||||
//
|
||||
// SYS-REQ-113
|
||||
func SetWildcard(data []byte, setValue []byte, keys ...string) ([]byte, error) {
|
||||
if wildcardIndex(keys) == -1 {
|
||||
return Set(data, setValue, keys...)
|
||||
}
|
||||
|
||||
var paths [][]string
|
||||
if err := expandWildcardPaths(data, nil, keys, &paths); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := data
|
||||
for _, path := range paths {
|
||||
var err error
|
||||
result, err = Set(result, setValue, path...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SYS-REQ-113
|
||||
func expandWildcardPaths(data []byte, concrete, remaining []string, paths *[][]string) error {
|
||||
wildcard := wildcardIndex(remaining)
|
||||
if wildcard == -1 {
|
||||
path := make([]string, len(concrete)+len(remaining))
|
||||
copy(path, concrete)
|
||||
copy(path[len(concrete):], remaining)
|
||||
*paths = append(*paths, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
arrayPath := make([]string, len(concrete)+wildcard)
|
||||
copy(arrayPath, concrete)
|
||||
copy(arrayPath[len(concrete):], remaining[:wildcard])
|
||||
|
||||
array, valueType, _, err := Get(data, arrayPath...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if valueType != Array {
|
||||
return MalformedArrayError
|
||||
}
|
||||
|
||||
index := 0
|
||||
_, err = ArrayEachErr(array, func(_ []byte, _ ValueType, _ int, parseErr error) error {
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
|
||||
nextPath := make([]string, len(arrayPath)+1)
|
||||
copy(nextPath, arrayPath)
|
||||
nextPath[len(arrayPath)] = "[" + strconv.Itoa(index) + "]"
|
||||
index++
|
||||
|
||||
return expandWildcardPaths(data, nextPath, remaining[wildcard+1:], paths)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// SYS-REQ-113
|
||||
func wildcardIndex(path []string) int {
|
||||
for i, component := range path {
|
||||
if component == wildcardPathComponent {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
+7
@@ -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
@@ -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
@@ -0,0 +1 @@
|
||||
comment: false
|
||||
+667
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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)
|
||||
)
|
||||
+59
@@ -1,5 +1,64 @@
|
||||
# Changelog
|
||||
|
||||
## 0.48.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
- Remove issue creation from logging integrations by @giortzisg in [#1340](https://github.com/getsentry/sentry-go/pull/1340)
|
||||
|
||||
### New Features ✨
|
||||
|
||||
- Add `ClientOptions.DataCollection` for granular control over data collected by automatic instrumentation, replacing the broad `SendDefaultPII` switch. `DataCollection` can independently configure automatic `user.*` population, cookies, request/response headers, HTTP bodies, and query parameters. When configured, it is the source of truth and `SendDefaultPII` is ignored. by @giortzisg in [#1339](https://github.com/getsentry/sentry-go/pull/1339)
|
||||
- For backwards compatibility, clients that do not configure `DataCollection` keep a best-effort mapping of the previous `SendDefaultPII` behavior. To opt in to the new defaults, pass an empty `DataCollection` and then restrict individual categories as needed.
|
||||
```go
|
||||
sentry.Init(sentry.ClientOptions{
|
||||
Dsn: "https://public@example.com/1",
|
||||
|
||||
// Opt in to the new data collection defaults. Omitted fields use their
|
||||
// defaults: user info, cookies, headers, query params, and supported HTTP
|
||||
// bodies are collected, with sensitive values filtered.
|
||||
DataCollection: &sentry.DataCollection{},
|
||||
})
|
||||
```
|
||||
- To opt in while disabling automatic user info and HTTP bodies, configure those fields explicitly:
|
||||
```go
|
||||
sentry.Init(sentry.ClientOptions{
|
||||
Dsn: "https://public@example.com/1",
|
||||
DataCollection: &sentry.DataCollection{
|
||||
UserInfo: sentry.Set(false),
|
||||
HTTPBodies: []sentry.BodyType{},
|
||||
},
|
||||
})
|
||||
```
|
||||
- PushScope shorthand now returns the new scope reference by @DoctorJohn in [#1335](https://github.com/getsentry/sentry-go/pull/1335)
|
||||
|
||||
### Bug Fixes 🐛
|
||||
|
||||
- Fix fiber route name when using middlewares by @giortzisg in [#1363](https://github.com/getsentry/sentry-go/pull/1363)
|
||||
- Omit empty event id for standalone client reports by @giortzisg in [#1362](https://github.com/getsentry/sentry-go/pull/1362)
|
||||
- Preserve '%' literal in log messages by @giortzisg in [#1358](https://github.com/getsentry/sentry-go/pull/1358)
|
||||
- Unaligned 64-bit atomic panic on 32-bit platforms in telemetry buffers by @Kirill-INQ in [#1355](https://github.com/getsentry/sentry-go/pull/1355)
|
||||
- Isolate event processor across clones by @giortzisg in [#1337](https://github.com/getsentry/sentry-go/pull/1337)
|
||||
|
||||
### Internal Changes 🔧
|
||||
|
||||
#### Deps
|
||||
|
||||
- Bump fiber/v2 to 2.52.14 by @giortzisg in [#1359](https://github.com/getsentry/sentry-go/pull/1359)
|
||||
- Bump actions/checkout from 6.0.3 to 7.0.0 by @dependabot in [#1349](https://github.com/getsentry/sentry-go/pull/1349)
|
||||
- Bump golangci/golangci-lint-action from 9.2.1 to 9.3.0 by @dependabot in [#1346](https://github.com/getsentry/sentry-go/pull/1346)
|
||||
- Bump codecov/codecov-action from 6.0.0 to 7.0.0 by @dependabot in [#1347](https://github.com/getsentry/sentry-go/pull/1347)
|
||||
- Bump actions/setup-go from 6.4.0 to 6.5.0 by @dependabot in [#1343](https://github.com/getsentry/sentry-go/pull/1343)
|
||||
- Bump golang.org/x/crypto to 0.52.0 and golang/x/net to 0.55.0 by @giortzisg in [#1341](https://github.com/getsentry/sentry-go/pull/1341)
|
||||
- Bump getsentry/github-workflows/validate-pr from c802283cd9075b7a2b7a32655019c21c21676e34 to 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 by @dependabot in [#1344](https://github.com/getsentry/sentry-go/pull/1344)
|
||||
|
||||
#### Other
|
||||
|
||||
- Remove changelog-preview and codecov actions by @giortzisg in [#1357](https://github.com/getsentry/sentry-go/pull/1357)
|
||||
- Add govulncheck audit action by @giortzisg in [#1342](https://github.com/getsentry/sentry-go/pull/1342)
|
||||
- Limit changelog-preview secret access by @giortzisg in [#1350](https://github.com/getsentry/sentry-go/pull/1350)
|
||||
- Move limited buffer under utils by @giortzisg in [#1338](https://github.com/getsentry/sentry-go/pull/1338)
|
||||
|
||||
## 0.47.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
+26
-3
@@ -172,9 +172,18 @@ type ClientOptions struct {
|
||||
// List of regexp strings that will be used to match against a transaction's
|
||||
// name. If a match is found, then the transaction will be dropped.
|
||||
IgnoreTransactions []string
|
||||
// Deprecated: Use DataCollection for granular control over what data the
|
||||
// SDK collects. When DataCollection is configured, SendDefaultPII is
|
||||
// ignored.
|
||||
//
|
||||
// If this flag is enabled, certain personally identifiable information (PII) is added by active integrations.
|
||||
// By default, no such data is sent.
|
||||
SendDefaultPII bool
|
||||
// DataCollection configures what data the SDK collects automatically. All fields are optional. By default
|
||||
// the SDK collects rich context for debugging while scrubbing sensitive values.
|
||||
//
|
||||
// See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection
|
||||
DataCollection *DataCollection
|
||||
// BeforeSend is called before error events are sent to Sentry.
|
||||
// You can use it to mutate the event or return nil to discard it.
|
||||
BeforeSend func(event *Event, hint *EventHint) *Event
|
||||
@@ -373,6 +382,9 @@ func NewClient(options ClientOptions) (*Client, error) {
|
||||
options.TraceIgnoreStatusCodes = [][]int{{404}}
|
||||
}
|
||||
|
||||
resolvedDataCollection := snapshotDataCollection(options.DataCollection, options.SendDefaultPII)
|
||||
options.DataCollection = cloneDataCollection(&resolvedDataCollection)
|
||||
|
||||
// SENTRYGODEBUG is a comma-separated list of key=value pairs (similar
|
||||
// to GODEBUG). It is not a supported feature: recognized debug options
|
||||
// may change any time.
|
||||
@@ -585,7 +597,18 @@ func (client *Client) externalTraceContextFromContext(ctx context.Context) (Trac
|
||||
// Options return ClientOptions for the current Client.
|
||||
func (client *Client) Options() ClientOptions {
|
||||
// Note: internally, consider using `client.options` instead of `client.Options()` to avoid copying the object each time.
|
||||
return client.options
|
||||
opts := client.options
|
||||
opts.DataCollection = cloneDataCollection(client.options.DataCollection)
|
||||
return opts
|
||||
}
|
||||
|
||||
// GetDataCollection returns a copy of the resolved data collection
|
||||
// configuration used by the client.
|
||||
func (client *Client) GetDataCollection() DataCollection {
|
||||
if client == nil || client.options.DataCollection == nil {
|
||||
return DataCollection{}
|
||||
}
|
||||
return *cloneDataCollection(client.options.DataCollection)
|
||||
}
|
||||
|
||||
// CaptureMessage captures an arbitrary message.
|
||||
@@ -686,7 +709,7 @@ func (client *Client) captureMetric(metric *Metric, _ *Scope) bool {
|
||||
|
||||
// Recover captures a panic.
|
||||
// Returns EventID if successfully, or nil if there's no error to recover from.
|
||||
func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID {
|
||||
func (client *Client) Recover(err any, hint *EventHint, scope EventModifier) *EventID {
|
||||
if err == nil {
|
||||
err = recover()
|
||||
}
|
||||
@@ -703,7 +726,7 @@ func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModif
|
||||
// Returns EventID if successfully, or nil if there's no error to recover from.
|
||||
func (client *Client) RecoverWithContext(
|
||||
ctx context.Context,
|
||||
err interface{},
|
||||
err any,
|
||||
hint *EventHint,
|
||||
scope EventModifier,
|
||||
) *EventID {
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package sentry
|
||||
|
||||
import "slices"
|
||||
|
||||
// CollectionMode controls how key-value data (headers, cookies, query params) is collected.
|
||||
//
|
||||
// Defaults to CollectionDenyList.
|
||||
type CollectionMode int
|
||||
|
||||
const (
|
||||
// CollectionDenyList keeps all keys and filters denied values.
|
||||
CollectionDenyList CollectionMode = iota
|
||||
|
||||
// CollectionOff disables collection of the category entirely.
|
||||
CollectionOff
|
||||
|
||||
// CollectionAllowList keeps all keys and sends real values only for allowed keys.
|
||||
CollectionAllowList
|
||||
)
|
||||
|
||||
// KeyValueCollectionBehavior configures how key-value data is collected and filtered.
|
||||
type KeyValueCollectionBehavior struct {
|
||||
// Mode controls the collection strategy.
|
||||
Mode CollectionMode
|
||||
// Terms is a list of additional terms used by the active mode.
|
||||
Terms []string
|
||||
}
|
||||
|
||||
// HeaderCollectionConfig configures how HTTP headers are collected for
|
||||
// requests and responses independently.
|
||||
type HeaderCollectionConfig struct {
|
||||
// Request configures collection of HTTP request headers.
|
||||
Request *KeyValueCollectionBehavior
|
||||
// Response configures collection of HTTP response headers.
|
||||
Response *KeyValueCollectionBehavior
|
||||
}
|
||||
|
||||
// BodyType identifies a category of HTTP body to collect.
|
||||
type BodyType string
|
||||
|
||||
const (
|
||||
// BodyIncomingRequest collects bodies from incoming HTTP requests
|
||||
// (server-side).
|
||||
BodyIncomingRequest BodyType = "incomingRequest"
|
||||
|
||||
// BodyOutgoingRequest collects bodies from outgoing HTTP requests
|
||||
// (client-side).
|
||||
BodyOutgoingRequest BodyType = "outgoingRequest"
|
||||
|
||||
// BodyIncomingResponse collects bodies from incoming HTTP responses
|
||||
// (client-side).
|
||||
BodyIncomingResponse BodyType = "incomingResponse"
|
||||
)
|
||||
|
||||
// DataCollection configures what data the SDK collects automatically.
|
||||
// All fields are optional. nil or zero-value fields use the documented
|
||||
// defaults, which collect rich context for debugging while scrubbing sensitive
|
||||
// values via a built-in denylist.
|
||||
//
|
||||
// See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection
|
||||
type DataCollection struct {
|
||||
// UserInfo controls automatic population of user.* fields from auto-instrumentation.
|
||||
//
|
||||
// This does NOT gate data explicitly set via Scope.SetUser(); that is
|
||||
// always attached. Defaults to true.
|
||||
UserInfo Option[bool]
|
||||
|
||||
// Cookies configures collection of HTTP cookies.
|
||||
//
|
||||
// Defaults to using the built-in DenyList.
|
||||
Cookies *KeyValueCollectionBehavior
|
||||
|
||||
// HTTPHeaders configures collection of HTTP request and response headers
|
||||
// independently.
|
||||
//
|
||||
// Defaults to both request and response using the built-in DenyList.
|
||||
HTTPHeaders *HeaderCollectionConfig
|
||||
|
||||
// HTTPBodies controls which HTTP body types are collected.
|
||||
//
|
||||
// Defaults to collecting all valid body types.
|
||||
HTTPBodies []BodyType
|
||||
|
||||
// QueryParams configures collection of URL query parameters.
|
||||
//
|
||||
// Defaults to using the built-in DenyList.
|
||||
QueryParams *KeyValueCollectionBehavior
|
||||
|
||||
// sensitiveTerms is the deny-list used for built-in sensitive-key
|
||||
// scrubbing.
|
||||
sensitiveTerms []string
|
||||
}
|
||||
|
||||
// cloneKeyValueCollectionBehavior returns a deep copy of b.
|
||||
func cloneKeyValueCollectionBehavior(b *KeyValueCollectionBehavior) *KeyValueCollectionBehavior {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := &KeyValueCollectionBehavior{Mode: b.Mode}
|
||||
if b.Terms != nil {
|
||||
cloned.Terms = slices.Clone(b.Terms)
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
// cloneHeaderCollectionConfig returns a deep copy of c.
|
||||
func cloneHeaderCollectionConfig(c *HeaderCollectionConfig) *HeaderCollectionConfig {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &HeaderCollectionConfig{
|
||||
Request: cloneKeyValueCollectionBehavior(c.Request),
|
||||
Response: cloneKeyValueCollectionBehavior(c.Response),
|
||||
}
|
||||
}
|
||||
|
||||
// cloneDataCollection returns a deep copy of dc.
|
||||
func cloneDataCollection(dc *DataCollection) *DataCollection {
|
||||
if dc == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := &DataCollection{
|
||||
UserInfo: dc.UserInfo,
|
||||
Cookies: cloneKeyValueCollectionBehavior(dc.Cookies),
|
||||
HTTPHeaders: cloneHeaderCollectionConfig(dc.HTTPHeaders),
|
||||
QueryParams: cloneKeyValueCollectionBehavior(dc.QueryParams),
|
||||
sensitiveTerms: dc.sensitiveTerms,
|
||||
}
|
||||
if dc.HTTPBodies != nil {
|
||||
cloned.HTTPBodies = slices.Clone(dc.HTTPBodies)
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
// allBodyTypes returns all valid body types.
|
||||
func allBodyTypes() []BodyType {
|
||||
return []BodyType{
|
||||
BodyIncomingRequest,
|
||||
BodyOutgoingRequest,
|
||||
BodyIncomingResponse,
|
||||
}
|
||||
}
|
||||
|
||||
// snapshotDataCollection builds a fully-populated DataCollection based on given options.
|
||||
// It handles any unspecified values by applying the defaults. If the given opts are nil, this
|
||||
// provides a best-effort snapshot to align with sendDefaultPII for backwards compatibility.
|
||||
func snapshotDataCollection(opts *DataCollection, sendDefaultPII bool) DataCollection {
|
||||
if opts == nil {
|
||||
return legacyDataCollection(sendDefaultPII)
|
||||
}
|
||||
return resolveDataCollection(opts)
|
||||
}
|
||||
|
||||
func resolveDataCollection(dc *DataCollection) DataCollection {
|
||||
var resolved DataCollection
|
||||
if cloned := cloneDataCollection(dc); cloned != nil {
|
||||
resolved = *cloned
|
||||
}
|
||||
|
||||
if !resolved.UserInfo.IsSet {
|
||||
resolved.UserInfo = Set(true)
|
||||
}
|
||||
if resolved.Cookies == nil {
|
||||
resolved.Cookies = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
if resolved.HTTPHeaders == nil {
|
||||
resolved.HTTPHeaders = &HeaderCollectionConfig{}
|
||||
}
|
||||
if resolved.HTTPHeaders.Request == nil {
|
||||
resolved.HTTPHeaders.Request = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
if resolved.HTTPHeaders.Response == nil {
|
||||
resolved.HTTPHeaders.Response = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
if resolved.HTTPBodies == nil {
|
||||
resolved.HTTPBodies = allBodyTypes()
|
||||
}
|
||||
if resolved.QueryParams == nil {
|
||||
resolved.QueryParams = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
func legacyDataCollection(sendDefaultPII bool) DataCollection {
|
||||
if sendDefaultPII {
|
||||
return resolveDataCollection(&DataCollection{
|
||||
UserInfo: Set(true),
|
||||
Cookies: &KeyValueCollectionBehavior{},
|
||||
HTTPHeaders: &HeaderCollectionConfig{Request: &KeyValueCollectionBehavior{}, Response: &KeyValueCollectionBehavior{}},
|
||||
HTTPBodies: allBodyTypes(),
|
||||
QueryParams: &KeyValueCollectionBehavior{},
|
||||
})
|
||||
}
|
||||
|
||||
return resolveDataCollection(&DataCollection{
|
||||
UserInfo: Set(false),
|
||||
HTTPBodies: []BodyType{},
|
||||
Cookies: &KeyValueCollectionBehavior{Mode: CollectionOff},
|
||||
HTTPHeaders: &HeaderCollectionConfig{
|
||||
Request: &KeyValueCollectionBehavior{Mode: CollectionDenyList},
|
||||
Response: &KeyValueCollectionBehavior{Mode: CollectionDenyList},
|
||||
},
|
||||
QueryParams: &KeyValueCollectionBehavior{Mode: CollectionDenyList},
|
||||
sensitiveTerms: extendedSensitiveTerms,
|
||||
})
|
||||
}
|
||||
|
||||
// extendedSensitiveTerms are additional privacy terms that cover
|
||||
// user-identifying data such as IP forwarding headers and user IDs. Used for
|
||||
// backwards compatibility with SendDefaultPII=false.
|
||||
var extendedSensitiveTerms = []string{
|
||||
"forwarded",
|
||||
"-ip",
|
||||
"remote-",
|
||||
"via",
|
||||
"-user",
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// defaultSensitiveTerms is the canonical list of case-insensitive,
|
||||
// partial-match terms used for scrubbing.
|
||||
//
|
||||
// See https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist
|
||||
var defaultSensitiveTerms = []string{
|
||||
"auth",
|
||||
"bearer",
|
||||
"credentials",
|
||||
"csrf",
|
||||
"identity",
|
||||
"jwt",
|
||||
"key",
|
||||
"passwd",
|
||||
"password",
|
||||
"pwd",
|
||||
"saml",
|
||||
"secret",
|
||||
"session",
|
||||
"sid",
|
||||
"sso",
|
||||
"token",
|
||||
"xsrf",
|
||||
}
|
||||
|
||||
// filteredValue is the replacement for sensitive values.
|
||||
const filteredValue = "[Filtered]"
|
||||
|
||||
// filterKeyValues applies a KeyValueCollectionBehavior to a map of key-value
|
||||
// pairs. Keys are always preserved and values are replaced with "[Filtered]".
|
||||
//
|
||||
// Returns nil when the mode is CollectionOff.
|
||||
func (dc DataCollection) filterKeyValues(data map[string]string, behavior *KeyValueCollectionBehavior) map[string]string {
|
||||
if behavior == nil {
|
||||
behavior = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
if behavior.Mode == CollectionOff {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(data))
|
||||
for k, v := range data {
|
||||
if dc.shouldFilterKey(k, behavior) {
|
||||
result[k] = filteredValue
|
||||
} else {
|
||||
result[k] = v
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// FilterRequestHeaders applies the configured request-header collection behavior.
|
||||
func (dc DataCollection) FilterRequestHeaders(headers map[string]string) map[string]string {
|
||||
var behavior *KeyValueCollectionBehavior
|
||||
if dc.HTTPHeaders != nil {
|
||||
behavior = dc.HTTPHeaders.Request
|
||||
}
|
||||
return dc.filterKeyValues(headers, behavior)
|
||||
}
|
||||
|
||||
// FilterResponseHeaders applies the configured response-header collection behavior.
|
||||
func (dc DataCollection) FilterResponseHeaders(headers map[string]string) map[string]string {
|
||||
var behavior *KeyValueCollectionBehavior
|
||||
if dc.HTTPHeaders != nil {
|
||||
behavior = dc.HTTPHeaders.Response
|
||||
}
|
||||
return dc.filterKeyValues(headers, behavior)
|
||||
}
|
||||
|
||||
// CollectHTTPBody reports whether the given body type should be collected.
|
||||
func (dc *DataCollection) CollectHTTPBody(bt BodyType) bool {
|
||||
if dc == nil || dc.HTTPBodies == nil {
|
||||
return true
|
||||
}
|
||||
for _, t := range dc.HTTPBodies {
|
||||
if t == bt {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CollectCookies reports whether cookies should be collected.
|
||||
func (dc *DataCollection) CollectCookies() bool {
|
||||
return dc == nil || dc.Cookies == nil || dc.Cookies.Mode != CollectionOff
|
||||
}
|
||||
|
||||
// CollectQueryParams reports whether query parameters should be collected.
|
||||
func (dc DataCollection) CollectQueryParams() bool {
|
||||
return dc.QueryParams == nil || dc.QueryParams.Mode != CollectionOff
|
||||
}
|
||||
|
||||
// FilterQueryString applies the configured query-parameter collection behavior.
|
||||
func (dc DataCollection) FilterQueryString(rawQuery string) string {
|
||||
if rawQuery == "" {
|
||||
return ""
|
||||
}
|
||||
values, _ := url.ParseQuery(rawQuery)
|
||||
return dc.filterURLValues(values, dc.QueryParams)
|
||||
}
|
||||
|
||||
// FilterURL applies query-parameter filtering to u and returns its redacted string form.
|
||||
func (dc DataCollection) FilterURL(u *url.URL) string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
filtered := *u
|
||||
filtered.RawQuery = dc.FilterQueryString(u.RawQuery)
|
||||
return filtered.Redacted()
|
||||
}
|
||||
|
||||
// FilterCookies applies the configured cookie collection behavior.
|
||||
func (dc DataCollection) FilterCookies(values []string) string {
|
||||
parsed := parseKeyValueStrings(values, ';')
|
||||
if len(parsed) == 0 {
|
||||
return ""
|
||||
}
|
||||
filtered := dc.filterKeyValues(parsed, dc.Cookies)
|
||||
if len(filtered) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
parts := make([]string, 0, len(filtered))
|
||||
for key, value := range filtered {
|
||||
parts = append(parts, key+"="+value)
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// FilterSetCookies applies the configured cookie collection behavior to
|
||||
// Set-Cookie header values.
|
||||
func (dc DataCollection) FilterSetCookies(values []string) string {
|
||||
filtered := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if cookie := dc.filterSetCookie(value); cookie != "" {
|
||||
filtered = append(filtered, cookie)
|
||||
}
|
||||
}
|
||||
return strings.Join(filtered, ", ")
|
||||
}
|
||||
|
||||
func (dc DataCollection) filterSetCookie(setCookie string) string {
|
||||
if !dc.CollectCookies() {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(setCookie, ";")
|
||||
name, value, ok := strings.Cut(parts[0], "=")
|
||||
name = strings.TrimSpace(name)
|
||||
if !ok || name == "" {
|
||||
return ""
|
||||
}
|
||||
if dc.shouldFilterKey(name, dc.Cookies) {
|
||||
value = filteredValue
|
||||
}
|
||||
parts[0] = name + "=" + value
|
||||
|
||||
for i := 1; i < len(parts); i++ {
|
||||
attribute, _, ok := strings.Cut(parts[i], "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if name := strings.TrimSpace(attribute); name != "" && dc.shouldFilterKey(name, dc.Cookies) {
|
||||
parts[i] = attribute + "=" + filteredValue
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(parts, ";")
|
||||
}
|
||||
|
||||
// FilterHTTPBody applies sensitive-key filtering to parseable HTTP body data.
|
||||
// Opaque raw bodies are replaced entirely.
|
||||
func (dc DataCollection) FilterHTTPBody(body []byte, contentType string) string {
|
||||
if len(body) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(contentType), "application/json") || looksLikeJSON(body) {
|
||||
var value any
|
||||
if err := json.Unmarshal(body, &value); err == nil {
|
||||
filteredJSON := dc.filterJSONValue(value, nil)
|
||||
filtered, err := json.Marshal(filteredJSON)
|
||||
if err == nil {
|
||||
return string(filtered)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(contentType), "application/x-www-form-urlencoded") {
|
||||
if values, err := url.ParseQuery(string(body)); err == nil {
|
||||
return dc.filterURLValues(values, nil)
|
||||
}
|
||||
}
|
||||
|
||||
return filteredValue
|
||||
}
|
||||
|
||||
func looksLikeJSON(body []byte) bool {
|
||||
trimmed := strings.TrimSpace(string(body))
|
||||
return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[")
|
||||
}
|
||||
|
||||
func (dc DataCollection) filterURLValues(values url.Values, behavior *KeyValueCollectionBehavior) string {
|
||||
if behavior == nil {
|
||||
behavior = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
if behavior.Mode == CollectionOff {
|
||||
return ""
|
||||
}
|
||||
for key := range values {
|
||||
if dc.shouldFilterKey(key, behavior) {
|
||||
values.Set(key, filteredValue)
|
||||
}
|
||||
}
|
||||
return strings.ReplaceAll(values.Encode(), url.QueryEscape(filteredValue), filteredValue)
|
||||
}
|
||||
|
||||
func (dc DataCollection) filterJSONValue(value any, behavior *KeyValueCollectionBehavior) any {
|
||||
return dc.filterJSONNode(value, behavior, false)
|
||||
}
|
||||
|
||||
// filterJSONNode recursively filters a decoded JSON value.
|
||||
func (dc DataCollection) filterJSONNode(value any, behavior *KeyValueCollectionBehavior, keyed bool) any {
|
||||
if behavior != nil && behavior.Mode == CollectionOff {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch value := value.(type) {
|
||||
case map[string]any:
|
||||
filtered := make(map[string]any, len(value))
|
||||
for key, child := range value {
|
||||
if dc.shouldFilterKey(key, behavior) {
|
||||
filtered[key] = filteredValue
|
||||
} else {
|
||||
filtered[key] = dc.filterJSONNode(child, behavior, true)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
case []any:
|
||||
filtered := make([]any, len(value))
|
||||
for i, child := range value {
|
||||
filtered[i] = dc.filterJSONNode(child, behavior, keyed)
|
||||
}
|
||||
return filtered
|
||||
default:
|
||||
if !keyed {
|
||||
return filteredValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// shouldFilterKey reports whether a key's value should be redacted under the
|
||||
// given behavior. It combines the built-in sensitive terms with the behavior's
|
||||
// user-provided terms.
|
||||
func (dc DataCollection) shouldFilterKey(key string, behavior *KeyValueCollectionBehavior) bool {
|
||||
if behavior == nil {
|
||||
behavior = &KeyValueCollectionBehavior{}
|
||||
}
|
||||
|
||||
sensitive := matchesDenyTerms(key, defaultSensitiveTerms) || matchesDenyTerms(key, dc.sensitiveTerms)
|
||||
|
||||
switch behavior.Mode {
|
||||
case CollectionOff:
|
||||
return true
|
||||
case CollectionAllowList:
|
||||
return sensitive || !matchesDenyTerms(key, behavior.Terms)
|
||||
default:
|
||||
return sensitive || matchesDenyTerms(key, behavior.Terms)
|
||||
}
|
||||
}
|
||||
|
||||
// matchesDenyTerms reports whether the key (case-insensitive) contains any of
|
||||
// the given terms as a substring.
|
||||
func matchesDenyTerms(key string, terms []string) bool {
|
||||
lower := strings.ToLower(key)
|
||||
for _, term := range terms {
|
||||
if strings.Contains(lower, strings.ToLower(term)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseKeyValueStrings splits strings like "a=1; b=2" into a map.
|
||||
// Malformed parts without '=' and parts with empty keys are skipped.
|
||||
func parseKeyValueStrings(values []string, separator rune) map[string]string {
|
||||
result := make(map[string]string)
|
||||
for _, value := range values {
|
||||
for _, part := range strings.Split(value, string(separator)) {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
key, value, ok := strings.Cut(part, "=")
|
||||
if !ok || strings.TrimSpace(key) == "" {
|
||||
continue
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
+6
-3
@@ -36,7 +36,6 @@ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/T
|
||||
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
|
||||
github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o=
|
||||
github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk=
|
||||
github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA=
|
||||
@@ -119,7 +118,6 @@ github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
|
||||
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
@@ -128,7 +126,6 @@ github.com/rogpeppe/fastuuid v1.2.0 h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi
|
||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
|
||||
github.com/shirou/gopsutil/v3 v3.23.2 h1:PAWSuiAszn7IhPMBtXsbSCafej7PqUOvY6YywlQUExU=
|
||||
github.com/shirou/gopsutil/v3 v3.23.2/go.mod h1:gv0aQw33GLo3pG8SiWKiQrbDzbRY1K80RyZJ7V4Th1M=
|
||||
@@ -147,6 +144,9 @@ github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7Am
|
||||
github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms=
|
||||
github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4=
|
||||
github.com/valyala/fasthttp v1.58.0/go.mod h1:SYXvHHaFp7QZHGKSHmoMipInhrI5StHrhDTYVEjK/Kw=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM=
|
||||
github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg=
|
||||
@@ -163,6 +163,7 @@ golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs
|
||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
@@ -184,6 +185,7 @@ golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZ
|
||||
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=
|
||||
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
@@ -192,6 +194,7 @@ golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
|
||||
|
||||
+21
-28
@@ -247,50 +247,43 @@ type Request struct {
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
}
|
||||
|
||||
func sendDefaultPIIEnabled(client *Client) bool {
|
||||
return client != nil && client.options.SendDefaultPII
|
||||
}
|
||||
|
||||
func newRequest(r *http.Request, sendDefaultPII bool) *Request {
|
||||
func newRequest(r *http.Request, client *Client) *Request {
|
||||
prot := protocol.SchemeHTTP
|
||||
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
|
||||
prot = protocol.SchemeHTTPS
|
||||
}
|
||||
url := fmt.Sprintf("%s://%s%s", prot, r.Host, r.URL.Path)
|
||||
|
||||
dc := client.GetDataCollection()
|
||||
|
||||
var cookies string
|
||||
var env map[string]string
|
||||
headers := map[string]string{}
|
||||
|
||||
if sendDefaultPII {
|
||||
// We read only the first Cookie header because of the specification:
|
||||
// https://tools.ietf.org/html/rfc6265#section-5.4
|
||||
// When the user agent generates an HTTP request, the user agent MUST NOT
|
||||
// attach more than one Cookie header field.
|
||||
cookies = r.Header.Get("Cookie")
|
||||
|
||||
headers = make(map[string]string, len(r.Header))
|
||||
for k, v := range r.Header {
|
||||
headers[k] = strings.Join(v, ",")
|
||||
headers := make(map[string]string, len(r.Header)+1)
|
||||
if dc.CollectCookies() {
|
||||
cookies = dc.FilterCookies(r.Header.Values("Cookie"))
|
||||
if cookies != "" {
|
||||
headers["Cookie"] = cookies
|
||||
}
|
||||
}
|
||||
for k, v := range r.Header {
|
||||
if strings.EqualFold(k, "Cookie") {
|
||||
continue
|
||||
}
|
||||
headers[k] = strings.Join(v, ",")
|
||||
}
|
||||
headers["Host"] = r.Host
|
||||
headers = dc.FilterRequestHeaders(headers)
|
||||
|
||||
var env map[string]string
|
||||
if dc.UserInfo.Value {
|
||||
if addr, port, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port}
|
||||
}
|
||||
} else {
|
||||
for k, v := range r.Header {
|
||||
if !IsSensitiveHeader(k) {
|
||||
headers[k] = strings.Join(v, ",")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headers["Host"] = r.Host
|
||||
|
||||
return &Request{
|
||||
URL: url,
|
||||
Method: r.Method,
|
||||
QueryString: r.URL.RawQuery,
|
||||
QueryString: dc.FilterQueryString(r.URL.RawQuery),
|
||||
Cookies: cookies,
|
||||
Headers: headers,
|
||||
Env: env,
|
||||
@@ -302,7 +295,7 @@ func newRequest(r *http.Request, sendDefaultPII bool) *Request {
|
||||
// NewRequest avoids operations that depend on network access. In particular, it
|
||||
// does not read r.Body.
|
||||
func NewRequest(r *http.Request) *Request {
|
||||
return newRequest(r, sendDefaultPIIEnabled(CurrentHub().Client()))
|
||||
return newRequest(r, CurrentHub().Client())
|
||||
}
|
||||
|
||||
// Mechanism is the mechanism by which an exception was generated and handled.
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
)
|
||||
|
||||
// MaxBodyBytes is the maximum number of bytes the SDK captures from an HTTP
|
||||
// body for attaching to events or spans. Bodies larger than this are dropped
|
||||
// rather than truncated, to avoid invalid partial structured payloads.
|
||||
const MaxBodyBytes = 10 * 1024
|
||||
|
||||
// ReadCloser combines an io.Reader and an io.Closer to implement io.ReadCloser.
|
||||
type ReadCloser struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// LimitedBuffer is like a bytes.Buffer, but limited to store at most Capacity
|
||||
// bytes. Any writes past the capacity are silently discarded, similar to
|
||||
// io.Discard.
|
||||
type LimitedBuffer struct {
|
||||
Capacity int
|
||||
|
||||
bytes.Buffer
|
||||
overflow bool
|
||||
}
|
||||
|
||||
// NewLimitedBuffer returns a LimitedBuffer with the given capacity.
|
||||
func NewLimitedBuffer(capacity int) *LimitedBuffer {
|
||||
return &LimitedBuffer{Capacity: capacity}
|
||||
}
|
||||
|
||||
// NewLimitedBufferFromBytes returns a LimitedBuffer initialized from b.
|
||||
func NewLimitedBufferFromBytes(capacity int, b []byte) *LimitedBuffer {
|
||||
buf := NewLimitedBuffer(capacity)
|
||||
if len(b) > capacity {
|
||||
buf.overflow = true
|
||||
b = b[:capacity]
|
||||
}
|
||||
buf.Buffer = *bytes.NewBuffer(b)
|
||||
return buf
|
||||
}
|
||||
|
||||
// Write implements io.Writer.
|
||||
func (b *LimitedBuffer) Write(p []byte) (n int, err error) {
|
||||
originalLen := len(p)
|
||||
if b.overflow {
|
||||
return originalLen, nil
|
||||
}
|
||||
left := b.Capacity - b.Len()
|
||||
if left < 0 {
|
||||
left = 0
|
||||
}
|
||||
if len(p) > left {
|
||||
b.overflow = true
|
||||
p = p[:left]
|
||||
}
|
||||
_, err = b.Buffer.Write(p)
|
||||
return originalLen, err
|
||||
}
|
||||
|
||||
// Overflow returns true if the LimitedBuffer discarded bytes written to it.
|
||||
func (b *LimitedBuffer) Overflow() bool {
|
||||
return b.overflow
|
||||
}
|
||||
|
||||
// ReadBody reads up to MaxBodyBytes from r and returns the bytes read.
|
||||
func ReadBody(r io.Reader) []byte {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r, MaxBodyBytes+1))
|
||||
if err != nil || len(data) == 0 || len(data) > MaxBodyBytes {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// This wrapper is derived from https://github.com/go-chi/chi/blob/master/middleware/wrap_writer.go
|
||||
// Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc.
|
||||
|
||||
// MIT License
|
||||
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
// this software and associated documentation files (the "Software"), to deal in
|
||||
// the Software without restriction, including without limitation the rights to
|
||||
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
// the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to
|
||||
// hook into various parts of the response process.
|
||||
|
||||
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter {
|
||||
_, fl := w.(http.Flusher)
|
||||
|
||||
bw := basicWriter{ResponseWriter: w, code: http.StatusOK}
|
||||
|
||||
if protoMajor == 2 {
|
||||
_, ps := w.(http.Pusher)
|
||||
if fl && ps {
|
||||
return &http2FancyWriter{bw}
|
||||
}
|
||||
} else {
|
||||
_, hj := w.(http.Hijacker)
|
||||
_, rf := w.(io.ReaderFrom)
|
||||
if fl && hj && rf {
|
||||
return &httpFancyWriter{bw}
|
||||
}
|
||||
}
|
||||
if fl {
|
||||
return &flushWriter{bw}
|
||||
}
|
||||
|
||||
return &bw
|
||||
}
|
||||
|
||||
// WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook
|
||||
// into various parts of the response process.
|
||||
type WrapResponseWriter interface {
|
||||
http.ResponseWriter
|
||||
// Status returns the HTTP status of the request, or 200 if one has not
|
||||
// yet been sent.
|
||||
Status() int
|
||||
// BytesWritten returns the total number of bytes sent to the client.
|
||||
BytesWritten() int
|
||||
// Tee causes the response body to be written to the given io.Writer in
|
||||
// addition to proxying the writes through. Only one io.Writer can be
|
||||
// tee'd to at once: setting a second one will overwrite the first.
|
||||
// Writes will be sent to the proxy before being written to this
|
||||
// io.Writer. It is illegal for the tee'd writer to be modified
|
||||
// concurrently with writes.
|
||||
Tee(io.Writer)
|
||||
// Unwrap returns the original proxied target.
|
||||
Unwrap() http.ResponseWriter
|
||||
}
|
||||
|
||||
// basicWriter wraps a http.ResponseWriter that implements the minimal
|
||||
// http.ResponseWriter interface.
|
||||
type basicWriter struct {
|
||||
http.ResponseWriter
|
||||
tee io.Writer
|
||||
code int
|
||||
bytes int
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (b *basicWriter) WriteHeader(code int) {
|
||||
if !b.wroteHeader {
|
||||
b.code = code
|
||||
b.wroteHeader = true
|
||||
}
|
||||
b.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (b *basicWriter) Write(buf []byte) (int, error) {
|
||||
b.maybeWriteHeader()
|
||||
n, err := b.ResponseWriter.Write(buf)
|
||||
if b.tee != nil {
|
||||
_, err2 := b.tee.Write(buf[:n])
|
||||
// Prefer errors generated by the proxied writer.
|
||||
if err == nil {
|
||||
err = err2
|
||||
}
|
||||
}
|
||||
b.bytes += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (b *basicWriter) maybeWriteHeader() {
|
||||
if !b.wroteHeader {
|
||||
b.WriteHeader(http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *basicWriter) Status() int {
|
||||
return b.code
|
||||
}
|
||||
|
||||
func (b *basicWriter) BytesWritten() int {
|
||||
return b.bytes
|
||||
}
|
||||
|
||||
func (b *basicWriter) Tee(w io.Writer) {
|
||||
b.tee = w
|
||||
}
|
||||
|
||||
func (b *basicWriter) Unwrap() http.ResponseWriter {
|
||||
return b.ResponseWriter
|
||||
}
|
||||
|
||||
type flushWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *flushWriter) Flush() {
|
||||
f.wroteHeader = true
|
||||
|
||||
fl := f.ResponseWriter.(http.Flusher)
|
||||
fl.Flush()
|
||||
}
|
||||
|
||||
var _ http.Flusher = &flushWriter{}
|
||||
|
||||
// httpFancyWriter is a HTTP writer that additionally satisfies
|
||||
// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case
|
||||
// of wrapping the http.ResponseWriter that package http gives you, in order to
|
||||
// make the proxied object support the full method set of the proxied object.
|
||||
type httpFancyWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *httpFancyWriter) Flush() {
|
||||
f.wroteHeader = true
|
||||
f.ResponseWriter.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return f.ResponseWriter.(http.Hijacker).Hijack()
|
||||
}
|
||||
|
||||
func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
|
||||
return f.ResponseWriter.(http.Pusher).Push(target, opts)
|
||||
}
|
||||
|
||||
func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
|
||||
if f.tee != nil {
|
||||
n, err := io.Copy(&f.basicWriter, r)
|
||||
f.bytes += int(n)
|
||||
return n, err
|
||||
}
|
||||
rf := f.ResponseWriter.(io.ReaderFrom)
|
||||
f.maybeWriteHeader()
|
||||
n, err := rf.ReadFrom(r)
|
||||
f.bytes += int(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
var _ http.Flusher = &httpFancyWriter{}
|
||||
var _ http.Hijacker = &httpFancyWriter{}
|
||||
var _ http.Pusher = &http2FancyWriter{}
|
||||
var _ io.ReaderFrom = &httpFancyWriter{}
|
||||
|
||||
// http2FancyWriter is a HTTP2 writer that additionally satisfies
|
||||
// http.Flusher, and io.ReaderFrom. It exists for the common case
|
||||
// of wrapping the http.ResponseWriter that package http gives you, in order to
|
||||
// make the proxied object support the full method set of the proxied object.
|
||||
type http2FancyWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *http2FancyWriter) Flush() {
|
||||
f.wroteHeader = true
|
||||
|
||||
f.basicWriter.ResponseWriter.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
var _ http.Flusher = &http2FancyWriter{}
|
||||
+1
-1
@@ -17,7 +17,7 @@ type Envelope struct {
|
||||
// EnvelopeHeader represents the header of a Sentry envelope.
|
||||
type EnvelopeHeader struct {
|
||||
// EventID is the unique identifier for this event
|
||||
EventID string `json:"event_id"`
|
||||
EventID string `json:"event_id,omitempty"`
|
||||
|
||||
// SentAt is the timestamp when the event was sent from the SDK as string in RFC 3339 format.
|
||||
// Used for clock drift correction of the event timestamp. The time zone must be UTC.
|
||||
|
||||
+11
-9
@@ -46,8 +46,10 @@ type BucketedBuffer[T any] struct {
|
||||
timeout time.Duration
|
||||
lastFlushTime time.Time
|
||||
|
||||
offered int64
|
||||
dropped int64
|
||||
// atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain
|
||||
// mid-struct fields panic on 32-bit platforms (4-byte field alignment).
|
||||
offered atomic.Int64
|
||||
dropped atomic.Int64
|
||||
onDropped func(item T, reason string)
|
||||
}
|
||||
|
||||
@@ -94,7 +96,7 @@ func NewBucketedBuffer[T any](
|
||||
}
|
||||
|
||||
func (b *BucketedBuffer[T]) Offer(item T) bool {
|
||||
atomic.AddInt64(&b.offered, 1)
|
||||
b.offered.Add(1)
|
||||
|
||||
traceID := ""
|
||||
if ta, ok := any(item).(TraceAware); ok {
|
||||
@@ -152,7 +154,7 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool {
|
||||
oldestBucket := b.buckets[b.head]
|
||||
if oldestBucket == nil {
|
||||
b.recordDroppedItem(item)
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(item, "buffer_full_invalid_state")
|
||||
}
|
||||
@@ -162,7 +164,7 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool {
|
||||
delete(b.traceIndex, oldestBucket.traceID)
|
||||
}
|
||||
droppedCount := len(oldestBucket.items)
|
||||
atomic.AddInt64(&b.dropped, int64(droppedCount))
|
||||
b.dropped.Add(int64(droppedCount))
|
||||
for _, di := range oldestBucket.items {
|
||||
b.recordDroppedItem(di)
|
||||
if b.onDropped != nil {
|
||||
@@ -183,14 +185,14 @@ func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool {
|
||||
b.totalItems++
|
||||
return true
|
||||
case OverflowPolicyDropNewest:
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
b.recordDroppedItem(item)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(item, "buffer_full_drop_newest")
|
||||
}
|
||||
return false
|
||||
default:
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
b.recordDroppedItem(item)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(item, "unknown_overflow_policy")
|
||||
@@ -351,8 +353,8 @@ func (b *BucketedBuffer[T]) Utilization() float64 {
|
||||
}
|
||||
return float64(b.totalItems) / float64(b.itemCapacity)
|
||||
}
|
||||
func (b *BucketedBuffer[T]) OfferedCount() int64 { return atomic.LoadInt64(&b.offered) }
|
||||
func (b *BucketedBuffer[T]) DroppedCount() int64 { return atomic.LoadInt64(&b.dropped) }
|
||||
func (b *BucketedBuffer[T]) OfferedCount() int64 { return b.offered.Load() }
|
||||
func (b *BucketedBuffer[T]) DroppedCount() int64 { return b.dropped.Load() }
|
||||
func (b *BucketedBuffer[T]) AcceptedCount() int64 { return b.OfferedCount() - b.DroppedCount() }
|
||||
func (b *BucketedBuffer[T]) DropRate() float64 {
|
||||
off := b.OfferedCount()
|
||||
|
||||
+10
-8
@@ -30,8 +30,10 @@ type RingBuffer[T any] struct {
|
||||
timeout time.Duration
|
||||
lastFlushTime time.Time
|
||||
|
||||
offered int64
|
||||
dropped int64
|
||||
// atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain
|
||||
// mid-struct fields panic on 32-bit platforms (4-byte field alignment).
|
||||
offered atomic.Int64
|
||||
dropped atomic.Int64
|
||||
onDropped func(item T, reason string)
|
||||
}
|
||||
|
||||
@@ -72,7 +74,7 @@ func (b *RingBuffer[T]) SetDroppedCallback(callback func(item T, reason string))
|
||||
}
|
||||
|
||||
func (b *RingBuffer[T]) Offer(item T) bool {
|
||||
atomic.AddInt64(&b.offered, 1)
|
||||
b.offered.Add(1)
|
||||
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
@@ -91,7 +93,7 @@ func (b *RingBuffer[T]) Offer(item T) bool {
|
||||
b.head = (b.head + 1) % b.capacity
|
||||
b.tail = (b.tail + 1) % b.capacity
|
||||
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
b.recordDroppedItem(oldItem)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(oldItem, "buffer_full_drop_oldest")
|
||||
@@ -99,7 +101,7 @@ func (b *RingBuffer[T]) Offer(item T) bool {
|
||||
return true
|
||||
|
||||
case OverflowPolicyDropNewest:
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
b.recordDroppedItem(item)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(item, "buffer_full_drop_newest")
|
||||
@@ -107,7 +109,7 @@ func (b *RingBuffer[T]) Offer(item T) bool {
|
||||
return false
|
||||
|
||||
default:
|
||||
atomic.AddInt64(&b.dropped, 1)
|
||||
b.dropped.Add(1)
|
||||
b.recordDroppedItem(item)
|
||||
if b.onDropped != nil {
|
||||
b.onDropped(item, "unknown_overflow_policy")
|
||||
@@ -244,11 +246,11 @@ func (b *RingBuffer[T]) Utilization() float64 {
|
||||
}
|
||||
|
||||
func (b *RingBuffer[T]) OfferedCount() int64 {
|
||||
return atomic.LoadInt64(&b.offered)
|
||||
return b.offered.Load()
|
||||
}
|
||||
|
||||
func (b *RingBuffer[T]) DroppedCount() int64 {
|
||||
return atomic.LoadInt64(&b.dropped)
|
||||
return b.dropped.Load()
|
||||
}
|
||||
|
||||
func (b *RingBuffer[T]) AcceptedCount() int64 {
|
||||
|
||||
+10
-5
@@ -101,7 +101,7 @@ func (l *sentryLogger) Write(p []byte) (int, error) {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]attribute.Value, args ...interface{}) {
|
||||
func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]attribute.Value, format bool, args ...interface{}) {
|
||||
if message == "" {
|
||||
return
|
||||
}
|
||||
@@ -138,6 +138,11 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
|
||||
attrs[k] = v
|
||||
}
|
||||
|
||||
body := message
|
||||
if format {
|
||||
body = fmt.Sprintf(message, args...)
|
||||
}
|
||||
|
||||
if len(args) > 0 {
|
||||
attrs["sentry.message.template"] = attribute.StringValue(message)
|
||||
for i, p := range args {
|
||||
@@ -151,14 +156,14 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
|
||||
SpanID: spanID,
|
||||
Level: level,
|
||||
Severity: severity,
|
||||
Body: fmt.Sprintf(message, args...),
|
||||
Body: body,
|
||||
Attributes: attrs,
|
||||
}
|
||||
log.approximateSize = computeLogSize(log)
|
||||
|
||||
client.captureLog(log, scope)
|
||||
if client.options.Debug {
|
||||
debuglog.Printf(message, args...)
|
||||
debuglog.Print(body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,7 +332,7 @@ func (e *logEntry) Uint64(key string, value uint64) LogEntry {
|
||||
}
|
||||
|
||||
func (e *logEntry) Emit(args ...interface{}) {
|
||||
e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes)
|
||||
e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes, false)
|
||||
|
||||
if e.level == LogLevelFatal {
|
||||
if e.shouldPanic {
|
||||
@@ -340,7 +345,7 @@ func (e *logEntry) Emit(args ...interface{}) {
|
||||
}
|
||||
|
||||
func (e *logEntry) Emitf(format string, args ...interface{}) {
|
||||
e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, args...)
|
||||
e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, true, args...)
|
||||
|
||||
if e.level == LogLevelFatal {
|
||||
if e.shouldPanic {
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package sentry
|
||||
|
||||
// Option represents an optional configuration value.
|
||||
//
|
||||
// The zero value is unset. Use Set to distinguish an explicitly configured
|
||||
// zero value, such as false, 0, or "", from an unset option.
|
||||
type Option[T any] struct {
|
||||
Value T
|
||||
IsSet bool
|
||||
}
|
||||
|
||||
// Set returns an Option containing v.
|
||||
func Set[T any](v T) Option[T] {
|
||||
return Option[T]{Value: v, IsSet: true}
|
||||
}
|
||||
|
||||
// Or returns the option value when set, or defaultValue otherwise.
|
||||
func (o Option[T]) Or(defaultValue T) T {
|
||||
if o.IsSet {
|
||||
return o.Value
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
+10
-61
@@ -1,7 +1,6 @@
|
||||
package sentry
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"maps"
|
||||
@@ -11,6 +10,7 @@ import (
|
||||
|
||||
"github.com/getsentry/sentry-go/attribute"
|
||||
"github.com/getsentry/sentry-go/internal/debuglog"
|
||||
"github.com/getsentry/sentry-go/internal/httputils"
|
||||
"github.com/getsentry/sentry-go/internal/ratelimit"
|
||||
"github.com/getsentry/sentry-go/report"
|
||||
)
|
||||
@@ -128,15 +128,15 @@ func (scope *Scope) SetRequest(r *http.Request) {
|
||||
}
|
||||
|
||||
// Don't buffer request body if we know it is oversized.
|
||||
if r.ContentLength > maxRequestBodyBytes {
|
||||
if r.ContentLength > httputils.MaxBodyBytes {
|
||||
return
|
||||
}
|
||||
// Don't buffer if there is no body.
|
||||
if r.Body == nil || r.Body == http.NoBody {
|
||||
return
|
||||
}
|
||||
buf := &limitedBuffer{Capacity: maxRequestBodyBytes}
|
||||
r.Body = readCloser{
|
||||
buf := httputils.NewLimitedBuffer(httputils.MaxBodyBytes)
|
||||
r.Body = httputils.ReadCloser{
|
||||
Reader: io.TeeReader(r.Body, buf),
|
||||
Closer: r.Body,
|
||||
}
|
||||
@@ -152,59 +152,7 @@ func (scope *Scope) SetRequestBody(b []byte) {
|
||||
scope.mu.Lock()
|
||||
defer scope.mu.Unlock()
|
||||
|
||||
capacity := maxRequestBodyBytes
|
||||
overflow := false
|
||||
if len(b) > capacity {
|
||||
overflow = true
|
||||
b = b[:capacity]
|
||||
}
|
||||
scope.requestBody = &limitedBuffer{
|
||||
Capacity: capacity,
|
||||
Buffer: *bytes.NewBuffer(b),
|
||||
overflow: overflow,
|
||||
}
|
||||
}
|
||||
|
||||
// maxRequestBodyBytes is the default maximum request body size to send to
|
||||
// Sentry.
|
||||
const maxRequestBodyBytes = 10 * 1024
|
||||
|
||||
// A limitedBuffer is like a bytes.Buffer, but limited to store at most Capacity
|
||||
// bytes. Any writes past the capacity are silently discarded, similar to
|
||||
// io.Discard.
|
||||
type limitedBuffer struct {
|
||||
Capacity int
|
||||
|
||||
bytes.Buffer
|
||||
overflow bool
|
||||
}
|
||||
|
||||
// Write implements io.Writer.
|
||||
func (b *limitedBuffer) Write(p []byte) (n int, err error) {
|
||||
// Silently ignore writes after overflow.
|
||||
if b.overflow {
|
||||
return len(p), nil
|
||||
}
|
||||
left := b.Capacity - b.Len()
|
||||
if left < 0 {
|
||||
left = 0
|
||||
}
|
||||
if len(p) > left {
|
||||
b.overflow = true
|
||||
p = p[:left]
|
||||
}
|
||||
return b.Buffer.Write(p)
|
||||
}
|
||||
|
||||
// Overflow returns true if the limitedBuffer discarded bytes written to it.
|
||||
func (b *limitedBuffer) Overflow() bool {
|
||||
return b.overflow
|
||||
}
|
||||
|
||||
// readCloser combines an io.Reader and an io.Closer to implement io.ReadCloser.
|
||||
type readCloser struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
scope.requestBody = httputils.NewLimitedBufferFromBytes(httputils.MaxBodyBytes, b)
|
||||
}
|
||||
|
||||
// SetAttributes adds attributes to the current scope.
|
||||
@@ -346,7 +294,7 @@ func (scope *Scope) Clone() *Scope {
|
||||
clone.level = scope.level
|
||||
clone.request = scope.request
|
||||
clone.requestBody = scope.requestBody
|
||||
clone.eventProcessors = scope.eventProcessors
|
||||
clone.eventProcessors = scope.eventProcessors[:len(scope.eventProcessors):len(scope.eventProcessors)]
|
||||
clone.propagationContext = scope.propagationContext
|
||||
clone.span = scope.span
|
||||
return clone
|
||||
@@ -463,7 +411,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
}
|
||||
|
||||
if event.Request == nil && scope.request != nil {
|
||||
event.Request = newRequest(scope.request, sendDefaultPIIEnabled(client))
|
||||
event.Request = newRequest(scope.request, client)
|
||||
// NOTE: The SDK does not attempt to send partial request body data.
|
||||
//
|
||||
// The reason being that Sentry's ingest pipeline and UI are optimized
|
||||
@@ -473,8 +421,9 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
//
|
||||
// Users can still send more data along their events if they want to,
|
||||
// for example using Event.Contexts.
|
||||
if scope.requestBody != nil && !scope.requestBody.Overflow() {
|
||||
event.Request.Data = string(scope.requestBody.Bytes())
|
||||
dc := client.GetDataCollection()
|
||||
if scope.requestBody != nil && !scope.requestBody.Overflow() && dc.CollectHTTPBody(BodyIncomingRequest) {
|
||||
event.Request.Data = dc.FilterHTTPBody(scope.requestBody.Bytes(), scope.request.Header.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// The version of the SDK.
|
||||
const SDKVersion = "0.47.0"
|
||||
const SDKVersion = "0.48.0"
|
||||
|
||||
// apiVersion is the minimum version of the Sentry API compatible with the
|
||||
// sentry-go SDK.
|
||||
@@ -101,9 +101,9 @@ func ConfigureScope(f func(scope *Scope)) {
|
||||
}
|
||||
|
||||
// PushScope is a shorthand for CurrentHub().PushScope.
|
||||
func PushScope() {
|
||||
func PushScope() *Scope {
|
||||
hub := CurrentHub()
|
||||
hub.PushScope()
|
||||
return hub.PushScope()
|
||||
}
|
||||
|
||||
// PopScope is a shorthand for CurrentHub().PopScope.
|
||||
|
||||
-39
@@ -111,45 +111,6 @@ func Pointer[T any](v T) *T {
|
||||
return &v
|
||||
}
|
||||
|
||||
var sensitiveHeaders = map[string]struct{}{
|
||||
"_csrf": {},
|
||||
"_csrf_token": {},
|
||||
"_session": {},
|
||||
"_xsrf": {},
|
||||
"api-key": {},
|
||||
"apikey": {},
|
||||
"auth": {},
|
||||
"authorization": {},
|
||||
"cookie": {},
|
||||
"credentials": {},
|
||||
"csrf": {},
|
||||
"csrf-token": {},
|
||||
"csrftoken": {},
|
||||
"ip-address": {},
|
||||
"passwd": {},
|
||||
"password": {},
|
||||
"private-key": {},
|
||||
"privatekey": {},
|
||||
"proxy-authorization": {},
|
||||
"remote-addr": {},
|
||||
"secret": {},
|
||||
"session": {},
|
||||
"sessionid": {},
|
||||
"token": {},
|
||||
"user-session": {},
|
||||
"x-api-key": {},
|
||||
"x-csrftoken": {},
|
||||
"x-forwarded-for": {},
|
||||
"x-real-ip": {},
|
||||
"xsrf-token": {},
|
||||
}
|
||||
|
||||
// IsSensitiveHeader reports whether a header or metadata key should be treated as sensitive.
|
||||
func IsSensitiveHeader(key string) bool {
|
||||
_, ok := sensitiveHeaders[strings.ToLower(key)]
|
||||
return ok
|
||||
}
|
||||
|
||||
// eventIdentifier returns a human-readable identifier for the event to be used in log messages.
|
||||
// Format: "<description> [<event-id>]".
|
||||
func eventIdentifier(event *Event) string {
|
||||
|
||||
+3
@@ -39,6 +39,9 @@ linters:
|
||||
- legacy
|
||||
- std-error-handling
|
||||
rules:
|
||||
- linters:
|
||||
- goconst
|
||||
path: lorem.go
|
||||
- linters:
|
||||
- misspell
|
||||
path: person.go
|
||||
|
||||
+2
-2
@@ -99,8 +99,8 @@ Support For :
|
||||
Unfortunately this library has some limitation
|
||||
|
||||
- It does not support private fields. Make sure your structs fields you intend to generate fake data for are public, it would otherwise trigger a panic. You can however omit fields using a tag skip `faker:"-"` on your private fields.
|
||||
- It does not support the `interface{}` data type. How could we generate anything without knowing its data type?
|
||||
- It does not support the `map[interface{}]interface{}`, `map[any_type]interface{}` & `map[interface{}]any_type` data types. Once again, we cannot generate values for an unknown data type.
|
||||
- It does not support the `any` (empty interface) data type. How could we generate anything without knowing its data type?
|
||||
- It does not support the `map[any]any`, `map[T]any` & `map[any]T` data types (where `T` is any concrete type). Once again, we cannot generate values for an unknown data type.
|
||||
- Some extra custom types can be supported IF AND ONLY IF extended with [AddProvider()](https://github.com/go-faker/faker/blob/7473ac7d8d0440d24addac302c73e13c08895764/faker.go#L303) please see [example](example_custom_faker_test.go#L46)
|
||||
- The `oneof` tag currently only supports `string`, the `int` types, and both `float32` & `float64`. Further support is coming soon (i.e. hex numbers, etc). See [example](example_with_tags_test.go#L53) for usage.
|
||||
|
||||
|
||||
+12
-12
@@ -42,10 +42,10 @@ func GetAddress() Addresser {
|
||||
|
||||
// Addresser is logical layer for Address
|
||||
type Addresser interface {
|
||||
Latitude(v reflect.Value) (interface{}, error)
|
||||
Longitude(v reflect.Value) (interface{}, error)
|
||||
RealWorld(v reflect.Value) (interface{}, error)
|
||||
CountryInfo(v reflect.Value) (interface{}, error)
|
||||
Latitude(v reflect.Value) (any, error)
|
||||
Longitude(v reflect.Value) (any, error)
|
||||
RealWorld(v reflect.Value) (any, error)
|
||||
CountryInfo(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Address struct
|
||||
@@ -56,7 +56,7 @@ func (i Address) latitude() float32 {
|
||||
}
|
||||
|
||||
// Latitude sets latitude of the address
|
||||
func (i Address) Latitude(v reflect.Value) (interface{}, error) {
|
||||
func (i Address) Latitude(v reflect.Value) (any, error) {
|
||||
kind := v.Kind()
|
||||
val := i.latitude()
|
||||
if kind == reflect.Float32 {
|
||||
@@ -70,7 +70,7 @@ func (i Address) longitude() float32 {
|
||||
}
|
||||
|
||||
// Longitude sets longitude of the address
|
||||
func (i Address) Longitude(v reflect.Value) (interface{}, error) {
|
||||
func (i Address) Longitude(v reflect.Value) (any, error) {
|
||||
kind := v.Kind()
|
||||
val := i.longitude()
|
||||
if kind == reflect.Float32 {
|
||||
@@ -87,18 +87,18 @@ func (i Address) countryInfo() CountryInfo {
|
||||
return countries[rand.Intn(len(countries))]
|
||||
}
|
||||
|
||||
func (i Address) CountryInfo(_ reflect.Value) (interface{}, error) {
|
||||
func (i Address) CountryInfo(_ reflect.Value) (any, error) {
|
||||
return i.countryInfo(), nil
|
||||
}
|
||||
|
||||
// RealWorld sets real world address
|
||||
func (i Address) RealWorld(_ reflect.Value) (interface{}, error) {
|
||||
func (i Address) RealWorld(_ reflect.Value) (any, error) {
|
||||
return i.realWorld(), nil
|
||||
}
|
||||
|
||||
// Longitude get fake longitude randomly
|
||||
func Longitude(opts ...options.OptionFunc) float64 {
|
||||
return singleFakeData(LONGITUDE, func() interface{} {
|
||||
return singleFakeData(LONGITUDE, func() any {
|
||||
address := Address{}
|
||||
return float64(address.longitude())
|
||||
}, opts...).(float64)
|
||||
@@ -106,7 +106,7 @@ func Longitude(opts ...options.OptionFunc) float64 {
|
||||
|
||||
// Latitude get fake latitude randomly
|
||||
func Latitude(opts ...options.OptionFunc) float64 {
|
||||
return singleFakeData(LATITUDE, func() interface{} {
|
||||
return singleFakeData(LATITUDE, func() any {
|
||||
address := Address{}
|
||||
return float64(address.latitude())
|
||||
}, opts...).(float64)
|
||||
@@ -127,7 +127,7 @@ type RealAddress struct {
|
||||
|
||||
// GetRealAddress get real world address randomly
|
||||
func GetRealAddress(opts ...options.OptionFunc) RealAddress {
|
||||
return singleFakeData(RealAddressTag, func() interface{} {
|
||||
return singleFakeData(RealAddressTag, func() any {
|
||||
address := Address{}
|
||||
return address.realWorld()
|
||||
}, opts...).(RealAddress)
|
||||
@@ -142,7 +142,7 @@ type CountryInfo struct {
|
||||
}
|
||||
|
||||
func GetCountryInfo(opts ...options.OptionFunc) CountryInfo {
|
||||
return singleFakeData(CountryInfoTag, func() interface{} {
|
||||
return singleFakeData(CountryInfoTag, func() any {
|
||||
address := Address{}
|
||||
return address.countryInfo()
|
||||
}, opts...).(CountryInfo)
|
||||
|
||||
+6
-6
@@ -19,9 +19,9 @@ func GetBlood(opts ...options.OptionFunc) Blooder {
|
||||
}
|
||||
|
||||
type Blooder interface {
|
||||
BloodType(v reflect.Value) (interface{}, error)
|
||||
BloodRHFactor(v reflect.Value) (interface{}, error)
|
||||
BloodGroup(v reflect.Value) (interface{}, error)
|
||||
BloodType(v reflect.Value) (any, error)
|
||||
BloodRHFactor(v reflect.Value) (any, error)
|
||||
BloodGroup(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Internet struct
|
||||
@@ -33,7 +33,7 @@ func (b Blood) bloodType() string {
|
||||
return randomElementFromSliceString(bloodTypes)
|
||||
}
|
||||
|
||||
func (b Blood) BloodType(v reflect.Value) (interface{}, error) {
|
||||
func (b Blood) BloodType(v reflect.Value) (any, error) {
|
||||
return b.bloodType(), nil
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ func (b Blood) bloodRhFactor() string {
|
||||
return randomElementFromSliceString(bloodRhFactors)
|
||||
}
|
||||
|
||||
func (b Blood) BloodRHFactor(v reflect.Value) (interface{}, error) {
|
||||
func (b Blood) BloodRHFactor(v reflect.Value) (any, error) {
|
||||
return b.bloodRhFactor(), nil
|
||||
}
|
||||
|
||||
@@ -49,6 +49,6 @@ func (b Blood) bloodGroup() string {
|
||||
return fmt.Sprintf("%s%s", b.bloodType(), b.bloodRhFactor())
|
||||
}
|
||||
|
||||
func (b Blood) BloodGroup(v reflect.Value) (interface{}, error) {
|
||||
func (b Blood) BloodGroup(v reflect.Value) (any, error) {
|
||||
return b.bloodGroup(), nil
|
||||
}
|
||||
+33
-33
@@ -606,17 +606,17 @@ const (
|
||||
|
||||
// A DateTimer contains random Time generators, returning time string in certain particular format
|
||||
type DateTimer interface {
|
||||
UnixTime(v reflect.Value) (interface{}, error)
|
||||
Date(v reflect.Value) (interface{}, error)
|
||||
Time(v reflect.Value) (interface{}, error)
|
||||
MonthName(v reflect.Value) (interface{}, error)
|
||||
Year(v reflect.Value) (interface{}, error)
|
||||
DayOfWeek(v reflect.Value) (interface{}, error)
|
||||
DayOfMonth(v reflect.Value) (interface{}, error)
|
||||
Timestamp(v reflect.Value) (interface{}, error)
|
||||
Century(v reflect.Value) (interface{}, error)
|
||||
TimeZone(v reflect.Value) (interface{}, error)
|
||||
TimePeriod(v reflect.Value) (interface{}, error)
|
||||
UnixTime(v reflect.Value) (any, error)
|
||||
Date(v reflect.Value) (any, error)
|
||||
Time(v reflect.Value) (any, error)
|
||||
MonthName(v reflect.Value) (any, error)
|
||||
Year(v reflect.Value) (any, error)
|
||||
DayOfWeek(v reflect.Value) (any, error)
|
||||
DayOfMonth(v reflect.Value) (any, error)
|
||||
Timestamp(v reflect.Value) (any, error)
|
||||
Century(v reflect.Value) (any, error)
|
||||
TimeZone(v reflect.Value) (any, error)
|
||||
TimePeriod(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// GetDateTimer returns a new DateTimer interface of DateTime
|
||||
@@ -634,7 +634,7 @@ func (d DateTime) unixtime() int64 {
|
||||
}
|
||||
|
||||
// UnixTime get unix time
|
||||
func (d DateTime) UnixTime(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) UnixTime(v reflect.Value) (any, error) {
|
||||
kind := v.Kind()
|
||||
var val int64
|
||||
if kind == reflect.Int64 {
|
||||
@@ -648,7 +648,7 @@ func (d DateTime) UnixTime(v reflect.Value) (interface{}, error) {
|
||||
|
||||
// UnixTime get unix time randomly
|
||||
func UnixTime(opts ...options.OptionFunc) int64 {
|
||||
return singleFakeData(UnixTimeTag, func() interface{} {
|
||||
return singleFakeData(UnixTimeTag, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.unixtime()
|
||||
}, opts...).(int64)
|
||||
@@ -659,13 +659,13 @@ func (d DateTime) date() string {
|
||||
}
|
||||
|
||||
// Date formats DateTime using example BaseDateFormat const
|
||||
func (d DateTime) Date(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) Date(v reflect.Value) (any, error) {
|
||||
return d.date(), nil
|
||||
}
|
||||
|
||||
// Date get fake date in string randomly
|
||||
func Date(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(DATE, func() interface{} {
|
||||
return singleFakeData(DATE, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.date()
|
||||
}, opts...).(string)
|
||||
@@ -676,13 +676,13 @@ func (d DateTime) time() string {
|
||||
}
|
||||
|
||||
// Time formats DateTime using example Time const
|
||||
func (d DateTime) Time(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) Time(v reflect.Value) (any, error) {
|
||||
return d.time(), nil
|
||||
}
|
||||
|
||||
// TimeString get time randomly in string format
|
||||
func TimeString(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TIME, func() interface{} {
|
||||
return singleFakeData(TIME, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.time()
|
||||
}, opts...).(string)
|
||||
@@ -693,13 +693,13 @@ func (d DateTime) monthName() string {
|
||||
}
|
||||
|
||||
// MonthName formats DateTime using example Month const
|
||||
func (d DateTime) MonthName(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) MonthName(v reflect.Value) (any, error) {
|
||||
return d.monthName(), nil
|
||||
}
|
||||
|
||||
// MonthName get month name randomly in string format
|
||||
func MonthName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(MonthNameTag, func() interface{} {
|
||||
return singleFakeData(MonthNameTag, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.monthName()
|
||||
}, opts...).(string)
|
||||
@@ -710,13 +710,13 @@ func (d DateTime) year() string {
|
||||
}
|
||||
|
||||
// Year formats DateTime using example Year const
|
||||
func (d DateTime) Year(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) Year(v reflect.Value) (any, error) {
|
||||
return d.year(), nil
|
||||
}
|
||||
|
||||
// YearString get year randomly in string format
|
||||
func YearString(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(YEAR, func() interface{} {
|
||||
return singleFakeData(YEAR, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.year()
|
||||
}, opts...).(string)
|
||||
@@ -727,13 +727,13 @@ func (d DateTime) dayOfWeek() string {
|
||||
}
|
||||
|
||||
// DayOfWeek formats DateTime using example Day const
|
||||
func (d DateTime) DayOfWeek(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) DayOfWeek(v reflect.Value) (any, error) {
|
||||
return d.dayOfWeek(), nil
|
||||
}
|
||||
|
||||
// DayOfWeek get day of week randomly in string format
|
||||
func DayOfWeek(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(DayOfWeekTag, func() interface{} {
|
||||
return singleFakeData(DayOfWeekTag, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.dayOfWeek()
|
||||
}, opts...).(string)
|
||||
@@ -744,13 +744,13 @@ func (d DateTime) dayOfMonth() string {
|
||||
}
|
||||
|
||||
// DayOfMonth formats DateTime using example DayOfMonth const
|
||||
func (d DateTime) DayOfMonth(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) DayOfMonth(v reflect.Value) (any, error) {
|
||||
return d.dayOfMonth(), nil
|
||||
}
|
||||
|
||||
// DayOfMonth get month randomly in string format
|
||||
func DayOfMonth(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(DayOfMonthTag, func() interface{} {
|
||||
return singleFakeData(DayOfMonthTag, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.dayOfMonth()
|
||||
}, opts...).(string)
|
||||
@@ -761,13 +761,13 @@ func (d DateTime) timestamp() string {
|
||||
}
|
||||
|
||||
// Timestamp formats DateTime using example Timestamp const
|
||||
func (d DateTime) Timestamp(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) Timestamp(v reflect.Value) (any, error) {
|
||||
return d.timestamp(), nil
|
||||
}
|
||||
|
||||
// Timestamp get timestamp randomly in string format: 2006-01-02 15:04:05
|
||||
func Timestamp(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TIMESTAMP, func() interface{} {
|
||||
return singleFakeData(TIMESTAMP, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.timestamp()
|
||||
}, opts...).(string)
|
||||
@@ -778,13 +778,13 @@ func (d DateTime) century() string {
|
||||
}
|
||||
|
||||
// Century returns a random century
|
||||
func (d DateTime) Century(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) Century(v reflect.Value) (any, error) {
|
||||
return d.century(), nil
|
||||
}
|
||||
|
||||
// Century get century randomly in string
|
||||
func Century(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(CENTURY, func() interface{} {
|
||||
return singleFakeData(CENTURY, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.century()
|
||||
}, opts...).(string)
|
||||
@@ -795,13 +795,13 @@ func (d DateTime) timezone() string {
|
||||
}
|
||||
|
||||
// TimeZone returns a random timezone
|
||||
func (d DateTime) TimeZone(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) TimeZone(v reflect.Value) (any, error) {
|
||||
return d.timezone(), nil
|
||||
}
|
||||
|
||||
// Timezone get timezone randomly in string
|
||||
func Timezone(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TIMEZONE, func() interface{} {
|
||||
return singleFakeData(TIMEZONE, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.timezone()
|
||||
}, opts...).(string)
|
||||
@@ -812,13 +812,13 @@ func (d DateTime) period() string {
|
||||
}
|
||||
|
||||
// TimePeriod formats DateTime using example TimePeriod const
|
||||
func (d DateTime) TimePeriod(v reflect.Value) (interface{}, error) {
|
||||
func (d DateTime) TimePeriod(v reflect.Value) (any, error) {
|
||||
return d.period(), nil
|
||||
}
|
||||
|
||||
// Timeperiod get timeperiod randomly in string (AM/PM)
|
||||
func Timeperiod(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TimePeriodTag, func() interface{} {
|
||||
return singleFakeData(TimePeriodTag, func() any {
|
||||
datetime := DateTime{}
|
||||
return datetime.period()
|
||||
}, opts...).(string)
|
||||
|
||||
+45
-27
@@ -12,6 +12,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
fakerErrors "github.com/go-faker/faker/v4/pkg/errors"
|
||||
@@ -124,7 +125,7 @@ func (m *mapperTagCustom) Load(key string) (interfaces.TaggedFunction, bool) {
|
||||
if ok {
|
||||
return tagFunc, ok
|
||||
}
|
||||
tagPureFunc, ok := mappedTagFunc.(func(v reflect.Value) (interface{}, error))
|
||||
tagPureFunc, ok := mappedTagFunc.(func(v reflect.Value) (any, error))
|
||||
if ok {
|
||||
return tagPureFunc, ok
|
||||
}
|
||||
@@ -290,7 +291,27 @@ var (
|
||||
SetRandomNumberBoundaries = options.SetRandomNumberBoundaries
|
||||
)
|
||||
|
||||
// mapperTagHasDefaults reports whether mapperTag currently holds the default
|
||||
// (no-option) generator functions. The common no-option case skips the
|
||||
// redundant re-store while this is true, avoiding repeated work and lock
|
||||
// contention under high volume. An option call overwrites mapperTag and clears
|
||||
// the flag, so the next no-option call restores the defaults.
|
||||
var mapperTagHasDefaults atomic.Bool
|
||||
|
||||
func initMapperTagWithOption(opts ...options.OptionFunc) {
|
||||
if len(opts) == 0 {
|
||||
if mapperTagHasDefaults.Load() {
|
||||
return
|
||||
}
|
||||
storeMapperTagWithOption()
|
||||
mapperTagHasDefaults.Store(true)
|
||||
return
|
||||
}
|
||||
storeMapperTagWithOption(opts...)
|
||||
mapperTagHasDefaults.Store(false)
|
||||
}
|
||||
|
||||
func storeMapperTagWithOption(opts ...options.OptionFunc) {
|
||||
mapperTag.Store(EmailTag, GetNetworker(opts...).Email)
|
||||
mapperTag.Store(MacAddressTag, GetNetworker(opts...).MacAddress)
|
||||
mapperTag.Store(DomainNameTag, GetNetworker(opts...).DomainName)
|
||||
@@ -310,11 +331,11 @@ func initOption(opt ...options.OptionFunc) *options.Options {
|
||||
|
||||
// FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data.
|
||||
// You don't need to Create your own data for your testing.
|
||||
func FakeData(a interface{}, opt ...options.OptionFunc) error {
|
||||
func FakeData(a any, opt ...options.OptionFunc) error {
|
||||
opts := initOption(opt...)
|
||||
reflectType := reflect.TypeOf(a)
|
||||
|
||||
if reflectType.Kind() != reflect.Ptr {
|
||||
if reflectType.Kind() != reflect.Pointer {
|
||||
return errors.New(fakerErrors.ErrValueNotPtr)
|
||||
}
|
||||
|
||||
@@ -401,7 +422,7 @@ func RemoveProvider(tag string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, error) {
|
||||
func getFakedValue(item any, opts *options.Options) (reflect.Value, error) {
|
||||
t := reflect.TypeOf(item)
|
||||
if t == nil {
|
||||
if opts.IgnoreInterface {
|
||||
@@ -418,7 +439,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro
|
||||
}()
|
||||
k := t.Kind()
|
||||
switch k {
|
||||
case reflect.Ptr:
|
||||
case reflect.Pointer:
|
||||
v := reflect.New(t.Elem())
|
||||
var val reflect.Value
|
||||
var err error
|
||||
@@ -454,7 +475,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro
|
||||
}
|
||||
v := reflect.MakeSlice(t, length, length)
|
||||
innerOpts := opts.Nested()
|
||||
for i := 0; i < length; i++ {
|
||||
for i := range length {
|
||||
val, err := getFakedValue(v.Index(i).Interface(), &innerOpts)
|
||||
if err != nil {
|
||||
return reflect.Value{}, err
|
||||
@@ -527,7 +548,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro
|
||||
}
|
||||
v := reflect.MakeMap(t)
|
||||
innerOpts := opts.Nested()
|
||||
for i := 0; i < length; i++ {
|
||||
for range length {
|
||||
keyInstance := reflect.New(t.Key()).Elem().Interface()
|
||||
key, err := getFakedValue(keyInstance, &innerOpts)
|
||||
if err != nil {
|
||||
@@ -558,7 +579,7 @@ func getFakedValue(item interface{}, opts *options.Options) (reflect.Value, erro
|
||||
|
||||
}
|
||||
|
||||
func getFakedValueForStruct(item interface{}, t reflect.Type, opts *options.Options) (reflect.Value, error) {
|
||||
func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (reflect.Value, error) {
|
||||
if structTypeProvider, f := opts.StructTypeProviders[t]; f {
|
||||
ft, err := structTypeProvider()
|
||||
return reflect.ValueOf(ft), err
|
||||
@@ -641,7 +662,7 @@ func getFakedValueForStruct(item interface{}, t reflect.Type, opts *options.Opti
|
||||
}
|
||||
value := v.Field(i).Interface()
|
||||
uniqueVal, _ := uniqueValues.Load(tags.fieldType)
|
||||
uniqueValArr, _ := uniqueVal.([]interface{})
|
||||
uniqueValArr, _ := uniqueVal.([]any)
|
||||
if slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found
|
||||
i--
|
||||
retry++
|
||||
@@ -724,12 +745,12 @@ type structTag struct {
|
||||
}
|
||||
|
||||
func setDataWithTag(v reflect.Value, tag string, opt options.Options) error {
|
||||
if v.Kind() != reflect.Ptr {
|
||||
if v.Kind() != reflect.Pointer {
|
||||
return errors.New(fakerErrors.ErrValueNotPtr)
|
||||
}
|
||||
v = reflect.Indirect(v)
|
||||
switch v.Kind() {
|
||||
case reflect.Ptr:
|
||||
case reflect.Pointer:
|
||||
if _, exist := mapperTag.Load(tag); !exist {
|
||||
newv := reflect.New(v.Type().Elem())
|
||||
if err := setDataWithTag(newv, tag, opt); err != nil {
|
||||
@@ -806,7 +827,7 @@ func userDefinedMap(v reflect.Value, tag string, opt options.Options) error {
|
||||
}
|
||||
innerOpt := opt.Nested()
|
||||
definedMap := reflect.MakeMap(v.Type())
|
||||
for i := 0; i < length; i++ {
|
||||
for range length {
|
||||
key, err := getValueWithTag(v.Type().Key(), tag, innerOpt)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -821,7 +842,7 @@ func userDefinedMap(v reflect.Value, tag string, opt options.Options) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getValueWithTag(t reflect.Type, tag string, opt options.Options) (interface{}, error) {
|
||||
func getValueWithTag(t reflect.Type, tag string, opt options.Options) (any, error) {
|
||||
switch t.Kind() {
|
||||
case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8,
|
||||
reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
|
||||
@@ -841,7 +862,7 @@ func getValueWithTag(t reflect.Type, tag string, opt options.Options) (interface
|
||||
}
|
||||
}
|
||||
|
||||
func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoundary) (interface{}, error) {
|
||||
func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoundary) (any, error) {
|
||||
switch t.Kind() {
|
||||
case reflect.Uint:
|
||||
return uint(randomIntegerWithBoundary(boundary)), nil
|
||||
@@ -868,7 +889,7 @@ func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoun
|
||||
}
|
||||
}
|
||||
|
||||
func getValueWithNoTag(t reflect.Type, opt options.Options) (interface{}, error) {
|
||||
func getValueWithNoTag(t reflect.Type, opt options.Options) (any, error) {
|
||||
switch t.Kind() {
|
||||
case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8,
|
||||
reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
|
||||
@@ -947,7 +968,7 @@ func userDefinedArray(v reflect.Value, tag string, opt options.Options) error {
|
||||
}
|
||||
|
||||
func userDefinedString(v reflect.Value, tag string, opt options.Options) error {
|
||||
var res interface{}
|
||||
var res any
|
||||
var err error
|
||||
|
||||
if tagFunc, ok := mapperTag.Load(tag); ok {
|
||||
@@ -970,7 +991,7 @@ func userDefinedString(v reflect.Value, tag string, opt options.Options) error {
|
||||
}
|
||||
|
||||
func userDefinedNumber(v reflect.Value, tag string) error {
|
||||
var res interface{}
|
||||
var res any
|
||||
var err error
|
||||
|
||||
if tagFunc, ok := mapperTag.Load(tag); ok {
|
||||
@@ -1014,7 +1035,7 @@ func extractSliceLengthFromTag(tag string, opt options.Options) (int, error) {
|
||||
return randomSliceAndMapSize(opt), nil //Returns random slice length if the sliceLength tag isn't set
|
||||
}
|
||||
|
||||
func extractStringFromTag(tag string, opts options.Options) (interface{}, error) {
|
||||
func extractStringFromTag(tag string, opts options.Options) (any, error) {
|
||||
var err error
|
||||
strlen := opts.RandomStringLength
|
||||
strlng := opts.StringLanguage
|
||||
@@ -1075,7 +1096,7 @@ func extractLangFromTag(tag string) (*interfaces.LangRuneBoundary, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func extractNumberFromTag(tag string, t reflect.Type) (interface{}, error) {
|
||||
func extractNumberFromTag(tag string, t reflect.Type) (any, error) {
|
||||
hasOneOf := strings.Contains(tag, ONEOF)
|
||||
hasBoundaryStart := strings.Contains(tag, BoundaryStart)
|
||||
hasBoundaryEnd := strings.Contains(tag, BoundaryEnd)
|
||||
@@ -1348,10 +1369,7 @@ func randomSliceAndMapSize(opt options.Options) int {
|
||||
maxSize = opt.RandomNestedMaxSliceSize
|
||||
minSize = opt.RandomNestedMinSliceSize
|
||||
}
|
||||
r := maxSize - minSize
|
||||
if r < 1 {
|
||||
r = 1
|
||||
}
|
||||
r := max(maxSize-minSize, 1)
|
||||
return minSize + rand.Intn(r)
|
||||
}
|
||||
|
||||
@@ -1413,11 +1431,11 @@ func RandomInt(parameters ...int) (p []int, err error) {
|
||||
return p, err
|
||||
}
|
||||
|
||||
func generateUnique(dataType string, fn func() interface{}) (interface{}, error) {
|
||||
for i := 0; i < maxRetry; i++ {
|
||||
func generateUnique(dataType string, fn func() any) (any, error) {
|
||||
for range maxRetry {
|
||||
value := fn()
|
||||
uniqueVal, _ := uniqueValues.Load(dataType)
|
||||
uniqueValArr, _ := uniqueVal.([]interface{})
|
||||
uniqueValArr, _ := uniqueVal.([]any)
|
||||
if !slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found
|
||||
uniqueValues.Store(dataType, append(uniqueValArr, value))
|
||||
return value, nil
|
||||
@@ -1426,7 +1444,7 @@ func generateUnique(dataType string, fn func() interface{}) (interface{}, error)
|
||||
return reflect.Value{}, fmt.Errorf(fakerErrors.ErrUniqueFailure, dataType)
|
||||
}
|
||||
|
||||
func singleFakeData(dataType string, fn func() interface{}, opts ...options.OptionFunc) interface{} {
|
||||
func singleFakeData(dataType string, fn func() any, opts ...options.OptionFunc) any {
|
||||
ops := initOption(opts...)
|
||||
if ops.GenerateUniqueValues {
|
||||
v, err := generateUnique(dataType, fn)
|
||||
|
||||
+30
-30
@@ -46,15 +46,15 @@ func GetNetworker(opts ...options.OptionFunc) Networker {
|
||||
|
||||
// Networker is logical layer for Internet
|
||||
type Networker interface {
|
||||
Email(v reflect.Value) (interface{}, error)
|
||||
MacAddress(v reflect.Value) (interface{}, error)
|
||||
DomainName(v reflect.Value) (interface{}, error)
|
||||
URL(v reflect.Value) (interface{}, error)
|
||||
UserName(v reflect.Value) (interface{}, error)
|
||||
IPv4(v reflect.Value) (interface{}, error)
|
||||
IPv6(v reflect.Value) (interface{}, error)
|
||||
Password(v reflect.Value) (interface{}, error)
|
||||
Jwt(v reflect.Value) (interface{}, error)
|
||||
Email(v reflect.Value) (any, error)
|
||||
MacAddress(v reflect.Value) (any, error)
|
||||
DomainName(v reflect.Value) (any, error)
|
||||
URL(v reflect.Value) (any, error)
|
||||
UserName(v reflect.Value) (any, error)
|
||||
IPv4(v reflect.Value) (any, error)
|
||||
IPv6(v reflect.Value) (any, error)
|
||||
Password(v reflect.Value) (any, error)
|
||||
Jwt(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Internet struct
|
||||
@@ -84,13 +84,13 @@ func (internet Internet) email() (string, error) {
|
||||
}
|
||||
|
||||
// Email generates random email id
|
||||
func (internet Internet) Email(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) Email(v reflect.Value) (any, error) {
|
||||
return internet.email()
|
||||
}
|
||||
|
||||
// Email get email randomly in string
|
||||
func Email(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(EmailTag, func() interface{} {
|
||||
return singleFakeData(EmailTag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
r, err := i.email()
|
||||
@@ -103,20 +103,20 @@ func Email(opts ...options.OptionFunc) string {
|
||||
|
||||
func (internet Internet) macAddress() string {
|
||||
ip := make([]byte, 6)
|
||||
for i := 0; i < 6; i++ {
|
||||
for i := range 6 {
|
||||
ip[i] = byte(rand.Intn(256))
|
||||
}
|
||||
return net.HardwareAddr(ip).String()
|
||||
}
|
||||
|
||||
// MacAddress generates random MacAddress
|
||||
func (internet Internet) MacAddress(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) MacAddress(v reflect.Value) (any, error) {
|
||||
return internet.macAddress(), nil
|
||||
}
|
||||
|
||||
// MacAddress get mac address randomly in string
|
||||
func MacAddress(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(MacAddressTag, func() interface{} {
|
||||
return singleFakeData(MacAddressTag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
return i.macAddress()
|
||||
@@ -132,13 +132,13 @@ func (internet Internet) domainName() (string, error) {
|
||||
}
|
||||
|
||||
// DomainName generates random domain name
|
||||
func (internet Internet) DomainName(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) DomainName(v reflect.Value) (any, error) {
|
||||
return internet.domainName()
|
||||
}
|
||||
|
||||
// DomainName get email domain name in string
|
||||
func DomainName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(DomainNameTag, func() interface{} {
|
||||
return singleFakeData(DomainNameTag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
d, err := i.domainName()
|
||||
@@ -167,13 +167,13 @@ func (internet Internet) url() (string, error) {
|
||||
}
|
||||
|
||||
// URL generates random URL standardized in urlFormats const
|
||||
func (internet Internet) URL(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) URL(v reflect.Value) (any, error) {
|
||||
return internet.url()
|
||||
}
|
||||
|
||||
// URL get Url randomly in string
|
||||
func URL(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(URLTag, func() interface{} {
|
||||
return singleFakeData(URLTag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
u, err := i.url()
|
||||
@@ -189,13 +189,13 @@ func (internet Internet) username() (string, error) {
|
||||
}
|
||||
|
||||
// UserName generates random username
|
||||
func (internet Internet) UserName(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) UserName(v reflect.Value) (any, error) {
|
||||
return internet.username()
|
||||
}
|
||||
|
||||
// Username get username randomly in string
|
||||
func Username(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(UserNameTag, func() interface{} {
|
||||
return singleFakeData(UserNameTag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
u, err := i.username()
|
||||
@@ -209,20 +209,20 @@ func Username(opts ...options.OptionFunc) string {
|
||||
func (internet Internet) ipv4() string {
|
||||
size := 4
|
||||
ip := make([]byte, size)
|
||||
for i := 0; i < size; i++ {
|
||||
for i := range size {
|
||||
ip[i] = byte(rand.Intn(256))
|
||||
}
|
||||
return net.IP(ip).To4().String()
|
||||
}
|
||||
|
||||
// IPv4 generates random IPv4 address
|
||||
func (internet Internet) IPv4(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) IPv4(v reflect.Value) (any, error) {
|
||||
return internet.ipv4(), nil
|
||||
}
|
||||
|
||||
// IPv4 get IPv4 randomly in string
|
||||
func IPv4(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(IPV4Tag, func() interface{} {
|
||||
return singleFakeData(IPV4Tag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
return i.ipv4()
|
||||
@@ -232,20 +232,20 @@ func IPv4(opts ...options.OptionFunc) string {
|
||||
func (internet Internet) ipv6() string {
|
||||
size := 16
|
||||
ip := make([]byte, size)
|
||||
for i := 0; i < size; i++ {
|
||||
for i := range size {
|
||||
ip[i] = byte(rand.Intn(256))
|
||||
}
|
||||
return net.IP(ip).To16().String()
|
||||
}
|
||||
|
||||
// IPv6 generates random IPv6 address
|
||||
func (internet Internet) IPv6(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) IPv6(v reflect.Value) (any, error) {
|
||||
return internet.ipv6(), nil
|
||||
}
|
||||
|
||||
// IPv6 get IPv6 randomly in string
|
||||
func IPv6(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(IPV6Tag, func() interface{} {
|
||||
return singleFakeData(IPV6Tag, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
return i.ipv6()
|
||||
@@ -257,13 +257,13 @@ func (internet Internet) password() (string, error) {
|
||||
}
|
||||
|
||||
// Password returns a hashed password
|
||||
func (internet Internet) Password(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) Password(v reflect.Value) (any, error) {
|
||||
return internet.password()
|
||||
}
|
||||
|
||||
// Password get password randomly in string
|
||||
func Password(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(PASSWORD, func() interface{} {
|
||||
return singleFakeData(PASSWORD, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
p, err := i.password()
|
||||
@@ -284,13 +284,13 @@ func (internet Internet) jwt() (string, error) {
|
||||
}
|
||||
|
||||
// Jwt returns a jwt-like random string in xxxx.yyyy.zzzz style
|
||||
func (internet Internet) Jwt(v reflect.Value) (interface{}, error) {
|
||||
func (internet Internet) Jwt(v reflect.Value) (any, error) {
|
||||
return internet.jwt()
|
||||
}
|
||||
|
||||
// Jwt get jwt-like string
|
||||
func Jwt(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(JWT, func() interface{} {
|
||||
return singleFakeData(JWT, func() any {
|
||||
opt := options.BuildOptions(opts)
|
||||
i := Internet{fakerOption: *opt}
|
||||
p, err := i.jwt()
|
||||
|
||||
+10
-10
@@ -52,9 +52,9 @@ var wordList = []string{
|
||||
|
||||
// DataFaker generates randomized Words, Sentences and Paragraphs
|
||||
type DataFaker interface {
|
||||
Word(v reflect.Value) (interface{}, error)
|
||||
Sentence(v reflect.Value) (interface{}, error)
|
||||
Paragraph(v reflect.Value) (interface{}, error)
|
||||
Word(v reflect.Value) (any, error)
|
||||
Sentence(v reflect.Value) (any, error)
|
||||
Paragraph(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// GetLorem returns a new DataFaker interface of Lorem struct
|
||||
@@ -72,14 +72,14 @@ func (l Lorem) word() string {
|
||||
}
|
||||
|
||||
// Word returns a word from the wordList const
|
||||
func (l Lorem) Word(v reflect.Value) (interface{}, error) {
|
||||
func (l Lorem) Word(v reflect.Value) (any, error) {
|
||||
return l.word(), nil
|
||||
}
|
||||
|
||||
// Word get a word randomly in string
|
||||
func Word(opts ...options.OptionFunc) string {
|
||||
i := Lorem{}
|
||||
return singleFakeData(WORD, func() interface{} {
|
||||
return singleFakeData(WORD, func() any {
|
||||
return i.word()
|
||||
}, opts...).(string)
|
||||
}
|
||||
@@ -103,7 +103,7 @@ func (l Lorem) sentence(sentence *strings.Builder) *strings.Builder {
|
||||
}
|
||||
|
||||
// Sentence returns a sentence using the wordList const
|
||||
func (l Lorem) Sentence(_ reflect.Value) (interface{}, error) {
|
||||
func (l Lorem) Sentence(_ reflect.Value) (any, error) {
|
||||
sentence := l.sentence(&strings.Builder{})
|
||||
return sentence.String(), nil
|
||||
}
|
||||
@@ -111,7 +111,7 @@ func (l Lorem) Sentence(_ reflect.Value) (interface{}, error) {
|
||||
// Sentence get a sentence randomly in string
|
||||
func Sentence(opts ...options.OptionFunc) string {
|
||||
i := Lorem{}
|
||||
return singleFakeData(SENTENCE, func() interface{} {
|
||||
return singleFakeData(SENTENCE, func() any {
|
||||
return i.sentence(&strings.Builder{}).String()
|
||||
}, opts...).(string)
|
||||
}
|
||||
@@ -119,7 +119,7 @@ func Sentence(opts ...options.OptionFunc) string {
|
||||
func (l Lorem) paragraph() string {
|
||||
paragraph := &strings.Builder{}
|
||||
size := rand.Intn(10) + 1
|
||||
for i := 0; i < size; i++ {
|
||||
for i := range size {
|
||||
l.sentence(paragraph)
|
||||
if i != size-1 {
|
||||
paragraph.WriteString(" ")
|
||||
@@ -129,14 +129,14 @@ func (l Lorem) paragraph() string {
|
||||
}
|
||||
|
||||
// Paragraph returns a series of sentences as a paragraph using the wordList const
|
||||
func (l Lorem) Paragraph(v reflect.Value) (interface{}, error) {
|
||||
func (l Lorem) Paragraph(v reflect.Value) (any, error) {
|
||||
return l.paragraph(), nil
|
||||
}
|
||||
|
||||
// Paragraph get a paragraph randomly in string
|
||||
func Paragraph(opts ...options.OptionFunc) string {
|
||||
i := Lorem{}
|
||||
return singleFakeData(PARAGRAPH, func() interface{} {
|
||||
return singleFakeData(PARAGRAPH, func() any {
|
||||
return i.paragraph()
|
||||
}, opts...).(string)
|
||||
}
|
||||
+6
-6
@@ -38,8 +38,8 @@ func GetPayment() Render {
|
||||
|
||||
// Render contains Whole Random Credit Card Generators with their types
|
||||
type Render interface {
|
||||
CreditCardType(v reflect.Value) (interface{}, error)
|
||||
CreditCardNumber(v reflect.Value) (interface{}, error)
|
||||
CreditCardType(v reflect.Value) (any, error)
|
||||
CreditCardNumber(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Payment struct
|
||||
@@ -61,13 +61,13 @@ func (p Payment) cctype() string {
|
||||
|
||||
// CreditCardType returns one of the following credit values:
|
||||
// VISA, MasterCard, American Express, Discover, JCB and Diners Club
|
||||
func (p Payment) CreditCardType(v reflect.Value) (interface{}, error) {
|
||||
func (p Payment) CreditCardType(v reflect.Value) (any, error) {
|
||||
return p.cctype(), nil
|
||||
}
|
||||
|
||||
// CCType get a credit card type randomly in string (VISA, MasterCard, etc)
|
||||
func CCType(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(CreditCardType, func() interface{} {
|
||||
return singleFakeData(CreditCardType, func() any {
|
||||
p := Payment{}
|
||||
return p.cctype()
|
||||
}, opts...).(string)
|
||||
@@ -87,13 +87,13 @@ func (p Payment) ccnumber() string {
|
||||
}
|
||||
|
||||
// CreditCardNumber generated credit card number according to the card number rules
|
||||
func (p Payment) CreditCardNumber(v reflect.Value) (interface{}, error) {
|
||||
func (p Payment) CreditCardNumber(v reflect.Value) (any, error) {
|
||||
return p.ccnumber(), nil
|
||||
}
|
||||
|
||||
// CCNumber get a credit card number randomly in string (VISA, MasterCard, etc)
|
||||
func CCNumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(CreditCardNumber, func() interface{} {
|
||||
return singleFakeData(CreditCardNumber, func() any {
|
||||
p := Payment{}
|
||||
return p.ccnumber()
|
||||
}, opts...).(string)
|
||||
|
||||
+45
-45
@@ -9,23 +9,23 @@ import (
|
||||
|
||||
// Dowser provides interfaces to generate random logical Names with their initials
|
||||
type Dowser interface {
|
||||
TitleMale(v reflect.Value) (interface{}, error)
|
||||
TitleFeMale(v reflect.Value) (interface{}, error)
|
||||
FirstName(v reflect.Value) (interface{}, error)
|
||||
FirstNameMale(v reflect.Value) (interface{}, error)
|
||||
FirstNameFemale(v reflect.Value) (interface{}, error)
|
||||
LastName(v reflect.Value) (interface{}, error)
|
||||
Name(v reflect.Value) (interface{}, error)
|
||||
Gender(v reflect.Value) (interface{}, error)
|
||||
ChineseFirstName(v reflect.Value) (interface{}, error)
|
||||
ChineseLastName(v reflect.Value) (interface{}, error)
|
||||
ChineseName(v reflect.Value) (interface{}, error)
|
||||
RussianFirstNameMale(v reflect.Value) (interface{}, error)
|
||||
RussianMiddleNameMale(v reflect.Value) (interface{}, error)
|
||||
RussianLastNameMale(v reflect.Value) (interface{}, error)
|
||||
RussianFirstNameFemale(v reflect.Value) (interface{}, error)
|
||||
RussianMiddleNameFemale(v reflect.Value) (interface{}, error)
|
||||
RussianLastNameFemale(v reflect.Value) (interface{}, error)
|
||||
TitleMale(v reflect.Value) (any, error)
|
||||
TitleFeMale(v reflect.Value) (any, error)
|
||||
FirstName(v reflect.Value) (any, error)
|
||||
FirstNameMale(v reflect.Value) (any, error)
|
||||
FirstNameFemale(v reflect.Value) (any, error)
|
||||
LastName(v reflect.Value) (any, error)
|
||||
Name(v reflect.Value) (any, error)
|
||||
Gender(v reflect.Value) (any, error)
|
||||
ChineseFirstName(v reflect.Value) (any, error)
|
||||
ChineseLastName(v reflect.Value) (any, error)
|
||||
ChineseName(v reflect.Value) (any, error)
|
||||
RussianFirstNameMale(v reflect.Value) (any, error)
|
||||
RussianMiddleNameMale(v reflect.Value) (any, error)
|
||||
RussianLastNameMale(v reflect.Value) (any, error)
|
||||
RussianFirstNameFemale(v reflect.Value) (any, error)
|
||||
RussianMiddleNameFemale(v reflect.Value) (any, error)
|
||||
RussianLastNameFemale(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
var titlesMale = []string{
|
||||
@@ -637,13 +637,13 @@ func (p Person) titlemale() string {
|
||||
}
|
||||
|
||||
// TitleMale generates random titles for males
|
||||
func (p Person) TitleMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) TitleMale(v reflect.Value) (any, error) {
|
||||
return p.titlemale(), nil
|
||||
}
|
||||
|
||||
// TitleMale get a title male randomly in string ("Mr.", "Dr.", "Prof.", "Lord", "King", "Prince")
|
||||
func TitleMale(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TitleMaleTag, func() interface{} {
|
||||
return singleFakeData(TitleMaleTag, func() any {
|
||||
p := Person{}
|
||||
return p.titlemale()
|
||||
}, opts...).(string)
|
||||
@@ -654,13 +654,13 @@ func (p Person) titleFemale() string {
|
||||
}
|
||||
|
||||
// TitleFeMale generates random titles for females
|
||||
func (p Person) TitleFeMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) TitleFeMale(v reflect.Value) (any, error) {
|
||||
return p.titleFemale(), nil
|
||||
}
|
||||
|
||||
// TitleFemale get a title female randomly in string ("Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess")
|
||||
func TitleFemale(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TitleFemaleTag, func() interface{} {
|
||||
return singleFakeData(TitleFemaleTag, func() any {
|
||||
p := Person{}
|
||||
return p.titleFemale()
|
||||
}, opts...).(string)
|
||||
@@ -671,13 +671,13 @@ func (p Person) firstname() string {
|
||||
}
|
||||
|
||||
// FirstName returns first names
|
||||
func (p Person) FirstName(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) FirstName(v reflect.Value) (any, error) {
|
||||
return p.firstname(), nil
|
||||
}
|
||||
|
||||
// FirstName get fake firstname
|
||||
func FirstName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(FirstNameTag, func() interface{} {
|
||||
return singleFakeData(FirstNameTag, func() any {
|
||||
p := Person{}
|
||||
return p.firstname()
|
||||
}, opts...).(string)
|
||||
@@ -688,13 +688,13 @@ func (p Person) firstnamemale() string {
|
||||
}
|
||||
|
||||
// FirstNameMale returns first names for males
|
||||
func (p Person) FirstNameMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) FirstNameMale(v reflect.Value) (any, error) {
|
||||
return p.firstnamemale(), nil
|
||||
}
|
||||
|
||||
// FirstNameMale get fake firstname for male
|
||||
func FirstNameMale(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(FirstNameMaleTag, func() interface{} {
|
||||
return singleFakeData(FirstNameMaleTag, func() any {
|
||||
p := Person{}
|
||||
return p.firstnamemale()
|
||||
}, opts...).(string)
|
||||
@@ -705,13 +705,13 @@ func (p Person) firstnamefemale() string {
|
||||
}
|
||||
|
||||
// FirstNameFemale returns first names for females
|
||||
func (p Person) FirstNameFemale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) FirstNameFemale(v reflect.Value) (any, error) {
|
||||
return p.firstnamefemale(), nil
|
||||
}
|
||||
|
||||
// FirstNameFemale get fake firstname for female
|
||||
func FirstNameFemale(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(FirstNameFemaleTag, func() interface{} {
|
||||
return singleFakeData(FirstNameFemaleTag, func() any {
|
||||
p := Person{}
|
||||
return p.firstnamefemale()
|
||||
}, opts...).(string)
|
||||
@@ -722,13 +722,13 @@ func (p Person) lastname() string {
|
||||
}
|
||||
|
||||
// LastName returns last name
|
||||
func (p Person) LastName(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) LastName(v reflect.Value) (any, error) {
|
||||
return p.lastname(), nil
|
||||
}
|
||||
|
||||
// LastName get fake lastname
|
||||
func LastName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(LastNameTag, func() interface{} {
|
||||
return singleFakeData(LastNameTag, func() any {
|
||||
p := Person{}
|
||||
return p.lastname()
|
||||
}, opts...).(string)
|
||||
@@ -742,20 +742,20 @@ func (p Person) name() string {
|
||||
}
|
||||
|
||||
// Name returns a random name
|
||||
func (p Person) Name(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) Name(v reflect.Value) (any, error) {
|
||||
return p.name(), nil
|
||||
}
|
||||
|
||||
// Name get fake name
|
||||
func Name(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(NAME, func() interface{} {
|
||||
return singleFakeData(NAME, func() any {
|
||||
p := Person{}
|
||||
return p.name()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
// Gender returns a random gender
|
||||
func (p Person) Gender(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) Gender(v reflect.Value) (any, error) {
|
||||
return p.gender(), nil
|
||||
}
|
||||
|
||||
@@ -765,14 +765,14 @@ func (p Person) gender() string {
|
||||
|
||||
// Gender get fake gender
|
||||
func Gender(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(GENDER, func() interface{} {
|
||||
return singleFakeData(GENDER, func() any {
|
||||
p := Person{}
|
||||
return p.gender()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
// ChineseFirstName returns a random chinese first name
|
||||
func (p Person) ChineseFirstName(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) ChineseFirstName(v reflect.Value) (any, error) {
|
||||
return p.chineseFirstName(), nil
|
||||
}
|
||||
|
||||
@@ -782,14 +782,14 @@ func (p Person) chineseFirstName() string {
|
||||
|
||||
// ChineseFirstName get chinese first name
|
||||
func ChineseFirstName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ChineseFirstNameTag, func() interface{} {
|
||||
return singleFakeData(ChineseFirstNameTag, func() any {
|
||||
p := Person{}
|
||||
return p.chineseFirstName()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
// ChineseLastName returns a random chinese last name
|
||||
func (p Person) ChineseLastName(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) ChineseLastName(v reflect.Value) (any, error) {
|
||||
return p.chineseLastName(), nil
|
||||
}
|
||||
|
||||
@@ -799,14 +799,14 @@ func (p Person) chineseLastName() string {
|
||||
|
||||
// ChineseLastName get chinese lsst name
|
||||
func ChineseLastName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ChineseLastNameTag, func() interface{} {
|
||||
return singleFakeData(ChineseLastNameTag, func() any {
|
||||
p := Person{}
|
||||
return p.chineseLastName()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
// ChineseName returns a random nhinese name
|
||||
func (p Person) ChineseName(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) ChineseName(v reflect.Value) (any, error) {
|
||||
return p.chineseName(), nil
|
||||
}
|
||||
|
||||
@@ -816,7 +816,7 @@ func (p Person) chineseName() string {
|
||||
|
||||
// ChineseName get chinese lsst name
|
||||
func ChineseName(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ChineseNameTag, func() interface{} {
|
||||
return singleFakeData(ChineseNameTag, func() any {
|
||||
p := Person{}
|
||||
return p.chineseName()
|
||||
}, opts...).(string)
|
||||
@@ -847,31 +847,31 @@ func (p Person) russianLastNameFemale() string {
|
||||
}
|
||||
|
||||
// RussianFirstNameMale returns russian male firstname
|
||||
func (p Person) RussianFirstNameMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianFirstNameMale(v reflect.Value) (any, error) {
|
||||
return p.russianFirstNameMale(), nil
|
||||
}
|
||||
|
||||
// RussianMiddleNameMale returns russian male middlename
|
||||
func (p Person) RussianMiddleNameMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianMiddleNameMale(v reflect.Value) (any, error) {
|
||||
return p.russianMiddleNameMale(), nil
|
||||
}
|
||||
|
||||
// RussianLastNameMale returns russian male lastname
|
||||
func (p Person) RussianLastNameMale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianLastNameMale(v reflect.Value) (any, error) {
|
||||
return p.russianLastNameMale(), nil
|
||||
}
|
||||
|
||||
// RussianFirstNameFemale returns russian female firstname
|
||||
func (p Person) RussianFirstNameFemale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianFirstNameFemale(v reflect.Value) (any, error) {
|
||||
return p.russianFirstNameFemale(), nil
|
||||
}
|
||||
|
||||
// RussianMiddleNameFemale returns russian female middlename
|
||||
func (p Person) RussianMiddleNameFemale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianMiddleNameFemale(v reflect.Value) (any, error) {
|
||||
return p.russianMiddleNameFemale(), nil
|
||||
}
|
||||
|
||||
// RussianLastNameFemale returns russian female lastname
|
||||
func (p Person) RussianLastNameFemale(v reflect.Value) (interface{}, error) {
|
||||
func (p Person) RussianLastNameFemale(v reflect.Value) (any, error) {
|
||||
return p.russianLastNameFemale(), nil
|
||||
}
|
||||
+13
-13
@@ -17,9 +17,9 @@ func GetPhoner() Phoner {
|
||||
|
||||
// Phoner serves overall tele-phonic contact generator
|
||||
type Phoner interface {
|
||||
PhoneNumber(v reflect.Value) (interface{}, error)
|
||||
TollFreePhoneNumber(v reflect.Value) (interface{}, error)
|
||||
E164PhoneNumber(v reflect.Value) (interface{}, error)
|
||||
PhoneNumber(v reflect.Value) (any, error)
|
||||
TollFreePhoneNumber(v reflect.Value) (any, error)
|
||||
E164PhoneNumber(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Phone struct
|
||||
@@ -33,40 +33,40 @@ func (p Phone) phonenumber() string {
|
||||
}
|
||||
|
||||
// PhoneNumber generates phone numbers of type: "201-886-0269"
|
||||
func (p Phone) PhoneNumber(v reflect.Value) (interface{}, error) {
|
||||
func (p Phone) PhoneNumber(v reflect.Value) (any, error) {
|
||||
return p.phonenumber(), nil
|
||||
}
|
||||
|
||||
// Phonenumber get fake phone number
|
||||
func Phonenumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(PhoneNumber, func() interface{} {
|
||||
return singleFakeData(PhoneNumber, func() any {
|
||||
p := Phone{}
|
||||
return p.phonenumber()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
func (p Phone) tollfreephonenumber() string {
|
||||
out := ""
|
||||
var out strings.Builder
|
||||
boxDigitsStart := []string{"777", "888"}
|
||||
|
||||
ints, _ := RandomInt(1, 9)
|
||||
for index, v := range slice.IntToString(ints) {
|
||||
if index == 3 {
|
||||
out += "-"
|
||||
out.WriteString("-")
|
||||
}
|
||||
out += v
|
||||
out.WriteString(v)
|
||||
}
|
||||
return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], out)
|
||||
return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], out.String())
|
||||
}
|
||||
|
||||
// TollFreePhoneNumber generates phone numbers of type: "(888) 937-7238"
|
||||
func (p Phone) TollFreePhoneNumber(v reflect.Value) (interface{}, error) {
|
||||
func (p Phone) TollFreePhoneNumber(v reflect.Value) (any, error) {
|
||||
return p.tollfreephonenumber(), nil
|
||||
}
|
||||
|
||||
// TollFreePhoneNumber get fake TollFreePhoneNumber
|
||||
func TollFreePhoneNumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(TollFreeNumber, func() interface{} {
|
||||
return singleFakeData(TollFreeNumber, func() any {
|
||||
p := Phone{}
|
||||
return p.tollfreephonenumber()
|
||||
}, opts...).(string)
|
||||
@@ -84,13 +84,13 @@ func (p Phone) e164PhoneNumber() string {
|
||||
}
|
||||
|
||||
// E164PhoneNumber generates phone numbers of type: "+27113456789"
|
||||
func (p Phone) E164PhoneNumber(v reflect.Value) (interface{}, error) {
|
||||
func (p Phone) E164PhoneNumber(v reflect.Value) (any, error) {
|
||||
return p.e164PhoneNumber(), nil
|
||||
}
|
||||
|
||||
// E164PhoneNumber get fake E164PhoneNumber
|
||||
func E164PhoneNumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(E164PhoneNumberTag, func() interface{} {
|
||||
return singleFakeData(E164PhoneNumberTag, func() any {
|
||||
p := Phone{}
|
||||
return p.e164PhoneNumber()
|
||||
}, opts...).(string)
|
||||
|
||||
+2
-2
@@ -3,8 +3,8 @@ package interfaces
|
||||
import "reflect"
|
||||
|
||||
// CustomProviderFunction used as the standard layout function for custom providers
|
||||
type CustomProviderFunction func() (interface{}, error)
|
||||
type CustomProviderFunction func() (any, error)
|
||||
|
||||
// TaggedFunction used as the standard layout function for tag providers in struct.
|
||||
// This type also can be used for custom provider.
|
||||
type TaggedFunction func(v reflect.Value) (interface{}, error)
|
||||
type TaggedFunction func(v reflect.Value) (any, error)
|
||||
+2
-2
@@ -135,7 +135,7 @@ func BuildOptions(optFuncs []OptionFunc) *Options {
|
||||
func DefaultOption() *Options {
|
||||
ops := &Options{}
|
||||
ops.StructTypeProviders = make(map[reflect.Type]interfaces.CustomProviderFunction)
|
||||
ops.StructTypeProviders[reflect.TypeOf(time.Time{})] = func() (interface{}, error) {
|
||||
ops.StructTypeProviders[reflect.TypeFor[time.Time]()] = func() (any, error) {
|
||||
return time.Now().Add(time.Duration(rand.Int63())), nil
|
||||
}
|
||||
ops.MaxDepthOption = &MaxDepthOption{
|
||||
@@ -209,7 +209,7 @@ func WithMaxFieldDepthOption(depth int) OptionFunc {
|
||||
}
|
||||
|
||||
// WithStructTypeProviders used for configuring the custom provider of struct type
|
||||
func WithStructTypeProviders(t interface{}, provider interfaces.CustomProviderFunction) OptionFunc {
|
||||
func WithStructTypeProviders(t any, provider interfaces.CustomProviderFunction) OptionFunc {
|
||||
if reflect.TypeOf(t).Kind() != reflect.Struct {
|
||||
panic(fakerErrors.ErrOnlyStructTypeSupported)
|
||||
}
|
||||
|
||||
+6
-17
@@ -1,17 +1,13 @@
|
||||
package slice
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Contains Check item in slice string type
|
||||
func Contains(slice []string, item string) bool {
|
||||
for _, s := range slice {
|
||||
if s == item {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(slice, item)
|
||||
}
|
||||
|
||||
// ContainsRune Check item in map rune type
|
||||
@@ -21,21 +17,14 @@ func ContainsRune(set map[rune]struct{}, item rune) bool {
|
||||
}
|
||||
|
||||
// ContainsValue check if value exists in slice, no matter its type
|
||||
func ContainsValue(slice []interface{}, value interface{}) bool {
|
||||
for _, v := range slice {
|
||||
if v == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
func ContainsValue(slice []any, value any) bool {
|
||||
return slices.Contains(slice, value)
|
||||
}
|
||||
|
||||
// IntToString Convert slice int to slice string
|
||||
func IntToString(intSl []int) (str []string) {
|
||||
for i := range intSl {
|
||||
number := intSl[i]
|
||||
text := strconv.Itoa(number)
|
||||
str = append(str, text)
|
||||
for _, number := range intSl {
|
||||
str = append(str, strconv.Itoa(number))
|
||||
}
|
||||
return str
|
||||
}
|
||||
+8
-8
@@ -34,9 +34,9 @@ var currencies = []string{
|
||||
|
||||
// Money provides an interface to generate a custom price with or without a random currency code
|
||||
type Money interface {
|
||||
Currency(v reflect.Value) (interface{}, error)
|
||||
Amount(v reflect.Value) (interface{}, error)
|
||||
AmountWithCurrency(v reflect.Value) (interface{}, error)
|
||||
Currency(v reflect.Value) (any, error)
|
||||
Amount(v reflect.Value) (any, error)
|
||||
AmountWithCurrency(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Price struct
|
||||
@@ -53,13 +53,13 @@ func (p Price) currency() string {
|
||||
}
|
||||
|
||||
// Currency returns a random currency from currencies
|
||||
func (p Price) Currency(v reflect.Value) (interface{}, error) {
|
||||
func (p Price) Currency(v reflect.Value) (any, error) {
|
||||
return p.currency(), nil
|
||||
}
|
||||
|
||||
// Currency get fake Currency (IDR, USD)
|
||||
func Currency(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(CurrencyTag, func() interface{} {
|
||||
return singleFakeData(CurrencyTag, func() any {
|
||||
p := Price{}
|
||||
return p.currency()
|
||||
}, opts...).(string)
|
||||
@@ -71,7 +71,7 @@ func (p Price) amount() float64 {
|
||||
|
||||
// Amount returns a random floating price amount
|
||||
// with a random precision of [1,2] up to (10**8 - 1)
|
||||
func (p Price) Amount(v reflect.Value) (interface{}, error) {
|
||||
func (p Price) Amount(v reflect.Value) (any, error) {
|
||||
kind := v.Kind()
|
||||
val := p.amount()
|
||||
if kind == reflect.Float32 {
|
||||
@@ -88,13 +88,13 @@ func (p Price) amountwithcurrency() string {
|
||||
}
|
||||
|
||||
// AmountWithCurrency combines both price and currency together
|
||||
func (p Price) AmountWithCurrency(v reflect.Value) (interface{}, error) {
|
||||
func (p Price) AmountWithCurrency(v reflect.Value) (any, error) {
|
||||
return p.amountwithcurrency(), nil
|
||||
}
|
||||
|
||||
// AmountWithCurrency get fake AmountWithCurrency USD 49257.100
|
||||
func AmountWithCurrency(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(AmountWithCurrencyTag, func() interface{} {
|
||||
return singleFakeData(AmountWithCurrencyTag, func() any {
|
||||
p := Price{}
|
||||
return p.amountwithcurrency()
|
||||
}, opts...).(string)
|
||||
|
||||
+12
-12
@@ -8,7 +8,7 @@ import (
|
||||
fakerErrors "github.com/go-faker/faker/v4/pkg/errors"
|
||||
)
|
||||
|
||||
func extractFloat64FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractFloat64FromTagArgs(args []string) (any, error) {
|
||||
bytes := 64
|
||||
var floatValues []float64
|
||||
for _, i := range args {
|
||||
@@ -23,7 +23,7 @@ func extractFloat64FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractFloat32FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractFloat32FromTagArgs(args []string) (any, error) {
|
||||
bytes := 32
|
||||
var floatValues []float32
|
||||
for _, i := range args {
|
||||
@@ -38,7 +38,7 @@ func extractFloat32FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractInt64FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractInt64FromTagArgs(args []string) (any, error) {
|
||||
bytes := 64
|
||||
var floatValues []int64
|
||||
for _, i := range args {
|
||||
@@ -53,7 +53,7 @@ func extractInt64FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractInt32FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractInt32FromTagArgs(args []string) (any, error) {
|
||||
bytes := 32
|
||||
var floatValues []int32
|
||||
for _, i := range args {
|
||||
@@ -68,7 +68,7 @@ func extractInt32FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractInt16FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractInt16FromTagArgs(args []string) (any, error) {
|
||||
bytes := 16
|
||||
var floatValues []int16
|
||||
for _, i := range args {
|
||||
@@ -83,7 +83,7 @@ func extractInt16FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractInt8FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractInt8FromTagArgs(args []string) (any, error) {
|
||||
bytes := 8
|
||||
var floatValues []int8
|
||||
for _, i := range args {
|
||||
@@ -98,7 +98,7 @@ func extractInt8FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractIntFromTagArgs(args []string) (interface{}, error) {
|
||||
func extractIntFromTagArgs(args []string) (any, error) {
|
||||
bytes := 0
|
||||
var floatValues []int
|
||||
for _, i := range args {
|
||||
@@ -113,7 +113,7 @@ func extractIntFromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractUint64FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractUint64FromTagArgs(args []string) (any, error) {
|
||||
bytes := 64
|
||||
var floatValues []uint64
|
||||
for _, i := range args {
|
||||
@@ -128,7 +128,7 @@ func extractUint64FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractUint32FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractUint32FromTagArgs(args []string) (any, error) {
|
||||
bytes := 32
|
||||
var floatValues []uint32
|
||||
for _, i := range args {
|
||||
@@ -143,7 +143,7 @@ func extractUint32FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractUint16FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractUint16FromTagArgs(args []string) (any, error) {
|
||||
bytes := 16
|
||||
var floatValues []uint16
|
||||
for _, i := range args {
|
||||
@@ -158,7 +158,7 @@ func extractUint16FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractUint8FromTagArgs(args []string) (interface{}, error) {
|
||||
func extractUint8FromTagArgs(args []string) (any, error) {
|
||||
bytes := 8
|
||||
var floatValues []uint8
|
||||
for _, i := range args {
|
||||
@@ -173,7 +173,7 @@ func extractUint8FromTagArgs(args []string) (interface{}, error) {
|
||||
return toRet, nil
|
||||
}
|
||||
|
||||
func extractUintFromTagArgs(args []string) (interface{}, error) {
|
||||
func extractUintFromTagArgs(args []string) (any, error) {
|
||||
bytes := 0
|
||||
var floatValues []uint
|
||||
for _, i := range args {
|
||||
|
||||
+2
-2
@@ -38,13 +38,13 @@ func GetUserAgent() UserAgenter {
|
||||
}
|
||||
|
||||
type UserAgenter interface {
|
||||
UserAgent(v reflect.Value) (interface{}, error)
|
||||
UserAgent(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// UserAgent implements logic loosely based on https://fakerphp.org/formatters/user-agent/.
|
||||
type UserAgent struct{}
|
||||
|
||||
func (ua UserAgent) UserAgent(reflect.Value) (interface{}, error) {
|
||||
func (ua UserAgent) UserAgent(reflect.Value) (any, error) {
|
||||
browserType := randomElementFromSliceString(browserTypes)
|
||||
switch browserType {
|
||||
case "chrome":
|
||||
|
||||
+6
-6
@@ -15,8 +15,8 @@ func GetIdentifier() Identifier {
|
||||
|
||||
// Identifier ...
|
||||
type Identifier interface {
|
||||
Digit(v reflect.Value) (interface{}, error)
|
||||
Hyphenated(v reflect.Value) (interface{}, error)
|
||||
Digit(v reflect.Value) (any, error)
|
||||
Hyphenated(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// UUID struct
|
||||
@@ -46,13 +46,13 @@ func (u UUID) hyphenated() (string, error) {
|
||||
}
|
||||
|
||||
// Hyphenated returns a 36 byte hyphenated UUID
|
||||
func (u UUID) Hyphenated(v reflect.Value) (interface{}, error) {
|
||||
func (u UUID) Hyphenated(v reflect.Value) (any, error) {
|
||||
return u.hyphenated()
|
||||
}
|
||||
|
||||
// UUIDHyphenated get fake Hyphenated UUID
|
||||
func UUIDHyphenated(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(HyphenatedID, func() interface{} {
|
||||
return singleFakeData(HyphenatedID, func() any {
|
||||
u := UUID{}
|
||||
res, _ := u.hyphenated()
|
||||
return res
|
||||
@@ -69,13 +69,13 @@ func (u UUID) digit() (string, error) {
|
||||
}
|
||||
|
||||
// Digit returns a 32 bytes UUID
|
||||
func (u UUID) Digit(v reflect.Value) (interface{}, error) {
|
||||
func (u UUID) Digit(v reflect.Value) (any, error) {
|
||||
return u.digit()
|
||||
}
|
||||
|
||||
// UUIDDigit get fake Digit UUID
|
||||
func UUIDDigit(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ID, func() interface{} {
|
||||
return singleFakeData(ID, func() any {
|
||||
u := UUID{}
|
||||
res, _ := u.digit()
|
||||
return res
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
//go:build !go1.21
|
||||
// +build !go1.21
|
||||
|
||||
/*
|
||||
Copyright 2019 The logr Authors.
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
//go:build go1.21
|
||||
// +build go1.21
|
||||
|
||||
/*
|
||||
Copyright 2019 The logr Authors.
|
||||
|
||||
+36
-11
@@ -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
@@ -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
@@ -1,5 +1,4 @@
|
||||
//go:build go1.21
|
||||
// +build go1.21
|
||||
|
||||
/*
|
||||
Copyright 2023 The logr Authors.
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
//go:build go1.21
|
||||
// +build go1.21
|
||||
|
||||
/*
|
||||
Copyright 2023 The logr Authors.
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
//go:build go1.21
|
||||
// +build go1.21
|
||||
|
||||
/*
|
||||
Copyright 2023 The logr Authors.
|
||||
|
||||
+12
@@ -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
|
||||
|
||||
+10
-3
@@ -28,7 +28,10 @@ TEXT ·buildDtable_asm(SB), $0-24
|
||||
init_main_loop:
|
||||
ADD R8<<1, R1, R15
|
||||
MOVH (R15), R9
|
||||
CMN $1, 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)
|
||||
@@ -126,9 +129,13 @@ build_table_main_table:
|
||||
RET
|
||||
|
||||
build_table_check1_ok:
|
||||
TST R1, R1
|
||||
AND $0xff, R1, R15
|
||||
AND $0xff, R1, R16
|
||||
TST R16, R15
|
||||
BNE build_table_check2_ok
|
||||
CMP R6, R7
|
||||
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)
|
||||
|
||||
+4
-4
@@ -670,9 +670,9 @@ error_overread:
|
||||
MOVD R16, ret+24(FP)
|
||||
RET
|
||||
|
||||
// skipped sequenceDecs_decode_bmi2 (BMI2 not available on arm64)
|
||||
// skipped sequenceDecs_decode_bmi2 (generic twin preferred on arm64)
|
||||
|
||||
// skipped sequenceDecs_decode_56_bmi2 (BMI2 not available on arm64)
|
||||
// skipped sequenceDecs_decode_56_bmi2 (generic twin preferred on arm64)
|
||||
|
||||
// func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool
|
||||
// Requires: SSE
|
||||
@@ -1966,7 +1966,7 @@ error_not_enough_space:
|
||||
MOVD R16, ret+24(FP)
|
||||
RET
|
||||
|
||||
// skipped sequenceDecs_decodeSync_bmi2 (BMI2 not available on arm64)
|
||||
// skipped sequenceDecs_decodeSync_bmi2 (generic twin preferred on arm64)
|
||||
|
||||
// func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
|
||||
// Requires: CMOV, SSE
|
||||
@@ -2702,4 +2702,4 @@ error_not_enough_space:
|
||||
MOVD R16, ret+24(FP)
|
||||
RET
|
||||
|
||||
// skipped sequenceDecs_decodeSync_safe_bmi2 (BMI2 not available on arm64)
|
||||
// skipped sequenceDecs_decodeSync_safe_bmi2 (generic twin preferred on arm64)
|
||||
+4
-3
@@ -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")
|
||||
|
||||
+5
-1
@@ -24,6 +24,7 @@ var (
|
||||
err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]"
|
||||
err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
|
||||
err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
|
||||
errInvalidSyntax = "invalid URN syntax [col %d]"
|
||||
)
|
||||
var _toStateActions []byte = []byte{
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
@@ -4358,7 +4359,7 @@ func (m *machine) Parse(input []byte) (*URN, error) {
|
||||
|
||||
if m.parsingMode != RFC8141Only {
|
||||
// Throw an error when:
|
||||
// - we are entering here matching the the prefix in the namespace identifier part
|
||||
// - we are entering here matching the prefix in the namespace identifier part
|
||||
// - looking ahead (3 chars) we find a colon
|
||||
if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" {
|
||||
m.err = fmt.Errorf(errNoUrnWithinID, pos)
|
||||
@@ -5026,6 +5027,9 @@ func (m *machine) Parse(input []byte) (*URN, error) {
|
||||
}
|
||||
|
||||
if m.cs < firstFinal || m.cs == enFail {
|
||||
if m.err == nil {
|
||||
m.err = fmt.Errorf(errInvalidSyntax, m.p)
|
||||
}
|
||||
return nil, m.err
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -24,6 +24,7 @@ var (
|
||||
err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]"
|
||||
err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
|
||||
err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]"
|
||||
errInvalidSyntax = "invalid URN syntax [col %d]"
|
||||
)
|
||||
|
||||
%%{
|
||||
@@ -48,7 +49,7 @@ action set_pre {
|
||||
action throw_pre_urn_err {
|
||||
if m.parsingMode != RFC8141Only {
|
||||
// Throw an error when:
|
||||
// - we are entering here matching the the prefix in the namespace identifier part
|
||||
// - we are entering here matching the prefix in the namespace identifier part
|
||||
// - looking ahead (3 chars) we find a colon
|
||||
if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" {
|
||||
m.err = fmt.Errorf(errNoUrnWithinID, pos)
|
||||
@@ -366,6 +367,9 @@ func (m *machine) Parse(input []byte) (*URN, error) {
|
||||
%% write exec;
|
||||
|
||||
if m.cs < first_final || m.cs == en_fail {
|
||||
if m.err == nil {
|
||||
m.err = fmt.Errorf(errInvalidSyntax, m.p)
|
||||
}
|
||||
return nil, m.err
|
||||
}
|
||||
|
||||
@@ -383,4 +387,4 @@ func (m *machine) WithParsingMode(x ParsingMode) {
|
||||
m.startParsingAt = en_scim_only
|
||||
}
|
||||
m.parsingModeSet = true
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
const errInvalidURN = "invalid URN: %s"
|
||||
|
||||
// URN represents an Uniform Resource Name.
|
||||
// URN represents a Uniform Resource Name.
|
||||
//
|
||||
// The general form represented is:
|
||||
//
|
||||
@@ -32,7 +32,7 @@ type URN struct {
|
||||
|
||||
// Normalize turns the receiving URN into its norm version.
|
||||
//
|
||||
// Which means: lowercase prefix, lowercase namespace identifier, and immutate namespace specific string chars (except <hex> tokens which are lowercased).
|
||||
// Which means: lowercase prefix, lowercase namespace identifier, and leave namespace-specific string chars unchanged (except <hex> tokens which are lowercased).
|
||||
func (u *URN) Normalize() *URN {
|
||||
return &URN{
|
||||
prefix: "urn",
|
||||
@@ -82,10 +82,10 @@ func (u *URN) String() string {
|
||||
return res
|
||||
}
|
||||
|
||||
// Parse is responsible to create an URN instance from a byte array matching the correct URN syntax (RFC 2141).
|
||||
// Parse is responsible for creating a URN instance from a byte array matching the correct URN syntax (RFC 2141).
|
||||
func Parse(u []byte, options ...Option) (*URN, bool) {
|
||||
urn, err := NewMachine(options...).Parse(u)
|
||||
if err != nil {
|
||||
if err != nil || urn == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
|
||||
+8
-1
@@ -7,6 +7,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [v3.27.3] - 2026-07-22
|
||||
|
||||
### Changed
|
||||
|
||||
- Various dependency upgrades
|
||||
|
||||
## [v3.27.2] - 2026-06-30
|
||||
|
||||
### Changed
|
||||
@@ -319,7 +325,8 @@ Here's a quick summary:
|
||||
- Add new `context.Context`-aware functions and methods, for both sql and go migrations.
|
||||
- Return error when no migration files found or dir is not a directory.
|
||||
|
||||
[Unreleased]: https://github.com/pressly/goose/compare/v3.27.2...HEAD
|
||||
[Unreleased]: https://github.com/pressly/goose/compare/v3.27.3...HEAD
|
||||
[v3.27.3]: https://github.com/pressly/goose/compare/v3.27.2...v3.27.3
|
||||
[v3.27.2]: https://github.com/pressly/goose/compare/v3.27.1...v3.27.2
|
||||
[v3.27.1]: https://github.com/pressly/goose/compare/v3.27.0...v3.27.1
|
||||
[v3.27.0]: https://github.com/pressly/goose/compare/v3.26.0...v3.27.0
|
||||
|
||||
vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go
Generated
Vendored
+1
-1
@@ -90,7 +90,7 @@ loop:
|
||||
s = skipSpace(s[1:])
|
||||
}
|
||||
}
|
||||
return
|
||||
return specs
|
||||
}
|
||||
|
||||
func skipSpace(s string) (rest string) {
|
||||
|
||||
Generated
Vendored
-49
@@ -1,49 +0,0 @@
|
||||
// Copyright 2021 The Prometheus 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.
|
||||
|
||||
//go:build !go1.17
|
||||
// +build !go1.17
|
||||
|
||||
package collectors
|
||||
|
||||
import "github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
// NewGoCollector returns a collector that exports metrics about the current Go
|
||||
// process. This includes memory stats. To collect those, runtime.ReadMemStats
|
||||
// is called. This requires to “stop the world”, which usually only happens for
|
||||
// garbage collection (GC). Take the following implications into account when
|
||||
// deciding whether to use the Go collector:
|
||||
//
|
||||
// 1. The performance impact of stopping the world is the more relevant the more
|
||||
// frequently metrics are collected. However, with Go1.9 or later the
|
||||
// stop-the-world time per metrics collection is very short (~25µs) so that the
|
||||
// performance impact will only matter in rare cases. However, with older Go
|
||||
// versions, the stop-the-world duration depends on the heap size and can be
|
||||
// quite significant (~1.7 ms/GiB as per
|
||||
// https://go-review.googlesource.com/c/go/+/34937).
|
||||
//
|
||||
// 2. During an ongoing GC, nothing else can stop the world. Therefore, if the
|
||||
// metrics collection happens to coincide with GC, it will only complete after
|
||||
// GC has finished. Usually, GC is fast enough to not cause problems. However,
|
||||
// with a very large heap, GC might take multiple seconds, which is enough to
|
||||
// cause scrape timeouts in common setups. To avoid this problem, the Go
|
||||
// collector will use the memstats from a previous collection if
|
||||
// runtime.ReadMemStats takes more than 1s. However, if there are no previously
|
||||
// collected memstats, or their collection is more than 5m ago, the collection
|
||||
// will block until runtime.ReadMemStats succeeds.
|
||||
//
|
||||
// NOTE: The problem is solved in Go 1.15, see
|
||||
// https://github.com/golang/go/issues/19812 for the related Go issue.
|
||||
func NewGoCollector() prometheus.Collector {
|
||||
return prometheus.NewGoCollector()
|
||||
}
|
||||
Generated
Vendored
+2
-2
@@ -90,13 +90,13 @@ func WithGoCollectorMemStatsMetricsDisabled() func(options *internal.GoCollector
|
||||
// GoRuntimeMetricsRule allow enabling and configuring particular group of runtime/metrics.
|
||||
// TODO(bwplotka): Consider adding ability to adjust buckets.
|
||||
type GoRuntimeMetricsRule struct {
|
||||
// Matcher represents RE2 expression will match the runtime/metrics from https://golang.bg/src/runtime/metrics/description.go
|
||||
// Matcher represents RE2 expression will match the runtime/metrics from https://pkg.go.dev/runtime/metrics
|
||||
// Use `regexp.MustCompile` or `regexp.Compile` to create this field.
|
||||
Matcher *regexp.Regexp
|
||||
}
|
||||
|
||||
// WithGoCollectorRuntimeMetrics allows enabling and configuring particular group of runtime/metrics.
|
||||
// See the list of metrics https://golang.bg/src/runtime/metrics/description.go (pick the Go version you use there!).
|
||||
// See the list of metrics https://pkg.go.dev/runtime/metrics (pick the Go version you use there!).
|
||||
// You can use this option in repeated manner, which will add new rules. The order of rules is important, the last rule
|
||||
// that matches particular metrics is applied.
|
||||
func WithGoCollectorRuntimeMetrics(rules ...GoRuntimeMetricsRule) func(options *internal.GoCollectorOptions) {
|
||||
|
||||
+7
-4
@@ -85,11 +85,12 @@ type CounterVecOpts struct {
|
||||
// Both internal tracking values are added up in the Write method. This has to
|
||||
// be taken into account when it comes to precision and overflow behavior.
|
||||
func NewCounter(opts CounterOpts) Counter {
|
||||
desc := NewDesc(
|
||||
desc := V2.NewDesc(
|
||||
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
|
||||
opts.Help,
|
||||
nil,
|
||||
UnconstrainedLabels(nil),
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
)
|
||||
if opts.now == nil {
|
||||
opts.now = time.Now
|
||||
@@ -205,6 +206,7 @@ func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec {
|
||||
opts.Help,
|
||||
opts.VariableLabels,
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
)
|
||||
if opts.now == nil {
|
||||
opts.now = time.Now
|
||||
@@ -349,10 +351,11 @@ type CounterFunc interface {
|
||||
//
|
||||
// Check out the ExampleGaugeFunc examples for the similar GaugeFunc.
|
||||
func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc {
|
||||
return newValueFunc(NewDesc(
|
||||
return newValueFunc(V2.NewDesc(
|
||||
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
|
||||
opts.Help,
|
||||
nil,
|
||||
UnconstrainedLabels(nil),
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
), CounterValue, function)
|
||||
}
|
||||
+32
-5
@@ -47,6 +47,8 @@ type Desc struct {
|
||||
fqName string
|
||||
// help provides some helpful information about this metric.
|
||||
help string
|
||||
// unit provides the unit of this metric.
|
||||
unit string
|
||||
// constLabelPairs contains precalculated DTO label pairs based on
|
||||
// the constant labels.
|
||||
constLabelPairs []*dto.LabelPair
|
||||
@@ -66,6 +68,16 @@ type Desc struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// DescOpt allows setting optional fields for NewDesc.
|
||||
type DescOpt func(*Desc)
|
||||
|
||||
// WithUnit sets the unit for a Desc.
|
||||
func WithUnit(unit string) DescOpt {
|
||||
return func(d *Desc) {
|
||||
d.unit = unit
|
||||
}
|
||||
}
|
||||
|
||||
// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
|
||||
// and will be reported on registration time. variableLabels and constLabels can
|
||||
// be nil if no such labels should be set. fqName must not be empty.
|
||||
@@ -89,14 +101,17 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
|
||||
//
|
||||
// For constLabels, the label values are constant. Therefore, they are fully
|
||||
// specified in the Desc. See the Collector example for a usage pattern.
|
||||
func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels) *Desc {
|
||||
func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels, opts ...DescOpt) *Desc {
|
||||
d := &Desc{
|
||||
fqName: fqName,
|
||||
help: help,
|
||||
variableLabels: variableLabels.compile(),
|
||||
}
|
||||
//nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme.
|
||||
if !model.NameValidationScheme.IsValidMetricName(fqName) {
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(d)
|
||||
}
|
||||
if !model.UTF8Validation.IsValidMetricName(fqName) {
|
||||
d.err = fmt.Errorf("%q is not a valid metric name", fqName)
|
||||
return d
|
||||
}
|
||||
@@ -150,11 +165,13 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const
|
||||
d.id = xxh.Sum64()
|
||||
// Sort labelNames so that order doesn't matter for the hash.
|
||||
sort.Strings(labelNames)
|
||||
// Now hash together (in this order) the help string and the sorted
|
||||
// Now hash together (in this order) the help string, the unit string and the sorted
|
||||
// label names.
|
||||
xxh.Reset()
|
||||
xxh.WriteString(help)
|
||||
xxh.Write(separatorByteSlice)
|
||||
xxh.WriteString(d.unit)
|
||||
xxh.Write(separatorByteSlice)
|
||||
for _, labelName := range labelNames {
|
||||
xxh.WriteString(labelName)
|
||||
xxh.Write(separatorByteSlice)
|
||||
@@ -182,6 +199,15 @@ func NewInvalidDesc(err error) *Desc {
|
||||
}
|
||||
}
|
||||
|
||||
// Err returns an error that occurred during construction, if any.
|
||||
//
|
||||
// Calling this method is optional. It can be used to detect construction
|
||||
// errors early, before invoking other methods on the Desc. If an error is
|
||||
// present, later operations may not behave as expected.
|
||||
func (d *Desc) Err() error {
|
||||
return d.err
|
||||
}
|
||||
|
||||
func (d *Desc) String() string {
|
||||
lpStrings := make([]string, 0, len(d.constLabelPairs))
|
||||
for _, lp := range d.constLabelPairs {
|
||||
@@ -202,9 +228,10 @@ func (d *Desc) String() string {
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: {%s}}",
|
||||
"Desc{fqName: %q, help: %q, unit: %q, constLabels: {%s}, variableLabels: {%s}}",
|
||||
d.fqName,
|
||||
d.help,
|
||||
d.unit,
|
||||
strings.Join(lpStrings, ","),
|
||||
strings.Join(vlStrings, ","),
|
||||
)
|
||||
|
||||
+4
-4
@@ -47,14 +47,14 @@ func (e *expvarCollector) Collect(ch chan<- Metric) {
|
||||
if expVar == nil {
|
||||
continue
|
||||
}
|
||||
var v interface{}
|
||||
var v any
|
||||
labels := make([]string, len(desc.variableLabels.names))
|
||||
if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
|
||||
ch <- NewInvalidMetric(desc, err)
|
||||
continue
|
||||
}
|
||||
var processValue func(v interface{}, i int)
|
||||
processValue = func(v interface{}, i int) {
|
||||
var processValue func(v any, i int)
|
||||
processValue = func(v any, i int) {
|
||||
if i >= len(labels) {
|
||||
copiedLabels := append(make([]string, 0, len(labels)), labels...)
|
||||
switch v := v.(type) {
|
||||
@@ -72,7 +72,7 @@ func (e *expvarCollector) Collect(ch chan<- Metric) {
|
||||
ch <- m
|
||||
return
|
||||
}
|
||||
vm, ok := v.(map[string]interface{})
|
||||
vm, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
+7
-4
@@ -76,11 +76,12 @@ type GaugeVecOpts struct {
|
||||
// scenarios for Gauges and Counters, where the former tends to be Set-heavy and
|
||||
// the latter Inc-heavy.
|
||||
func NewGauge(opts GaugeOpts) Gauge {
|
||||
desc := NewDesc(
|
||||
desc := V2.NewDesc(
|
||||
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
|
||||
opts.Help,
|
||||
nil,
|
||||
UnconstrainedLabels(nil),
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
)
|
||||
result := &gauge{desc: desc, labelPairs: desc.constLabelPairs}
|
||||
result.init(result) // Init self-collection.
|
||||
@@ -163,6 +164,7 @@ func (v2) NewGaugeVec(opts GaugeVecOpts) *GaugeVec {
|
||||
opts.Help,
|
||||
opts.VariableLabels,
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
)
|
||||
return &GaugeVec{
|
||||
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
|
||||
@@ -302,10 +304,11 @@ type GaugeFunc interface {
|
||||
// value of 1. Example:
|
||||
// https://github.com/prometheus/common/blob/8558a5b7db3c84fa38b4766966059a7bd5bfa2ee/version/info.go#L36-L56
|
||||
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc {
|
||||
return newValueFunc(NewDesc(
|
||||
return newValueFunc(V2.NewDesc(
|
||||
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
|
||||
opts.Help,
|
||||
nil,
|
||||
UnconstrainedLabels(nil),
|
||||
opts.ConstLabels,
|
||||
WithUnit(opts.Unit),
|
||||
), GaugeValue, function)
|
||||
}
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
// Copyright 2021 The Prometheus 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.
|
||||
|
||||
//go:build !go1.17
|
||||
// +build !go1.17
|
||||
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type goCollector struct {
|
||||
base baseGoCollector
|
||||
|
||||
// ms... are memstats related.
|
||||
msLast *runtime.MemStats // Previously collected memstats.
|
||||
msLastTimestamp time.Time
|
||||
msMtx sync.Mutex // Protects msLast and msLastTimestamp.
|
||||
msMetrics memStatsMetrics
|
||||
msRead func(*runtime.MemStats) // For mocking in tests.
|
||||
msMaxWait time.Duration // Wait time for fresh memstats.
|
||||
msMaxAge time.Duration // Maximum allowed age of old memstats.
|
||||
}
|
||||
|
||||
// NewGoCollector is the obsolete version of collectors.NewGoCollector.
|
||||
// See there for documentation.
|
||||
//
|
||||
// Deprecated: Use collectors.NewGoCollector instead.
|
||||
func NewGoCollector() Collector {
|
||||
msMetrics := goRuntimeMemStats()
|
||||
msMetrics = append(msMetrics, struct {
|
||||
desc *Desc
|
||||
eval func(*runtime.MemStats) float64
|
||||
valType ValueType
|
||||
}{
|
||||
// This metric is omitted in Go1.17+, see https://github.com/prometheus/client_golang/issues/842#issuecomment-861812034
|
||||
desc: NewDesc(
|
||||
memstatNamespace("gc_cpu_fraction"),
|
||||
"The fraction of this program's available CPU time used by the GC since the program started.",
|
||||
nil, nil,
|
||||
),
|
||||
eval: func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction },
|
||||
valType: GaugeValue,
|
||||
})
|
||||
return &goCollector{
|
||||
base: newBaseGoCollector(),
|
||||
msLast: &runtime.MemStats{},
|
||||
msRead: runtime.ReadMemStats,
|
||||
msMaxWait: time.Second,
|
||||
msMaxAge: 5 * time.Minute,
|
||||
msMetrics: msMetrics,
|
||||
}
|
||||
}
|
||||
|
||||
// Describe returns all descriptions of the collector.
|
||||
func (c *goCollector) Describe(ch chan<- *Desc) {
|
||||
c.base.Describe(ch)
|
||||
for _, i := range c.msMetrics {
|
||||
ch <- i.desc
|
||||
}
|
||||
}
|
||||
|
||||
// Collect returns the current state of all metrics of the collector.
|
||||
func (c *goCollector) Collect(ch chan<- Metric) {
|
||||
var (
|
||||
ms = &runtime.MemStats{}
|
||||
done = make(chan struct{})
|
||||
)
|
||||
// Start reading memstats first as it might take a while.
|
||||
go func() {
|
||||
c.msRead(ms)
|
||||
c.msMtx.Lock()
|
||||
c.msLast = ms
|
||||
c.msLastTimestamp = time.Now()
|
||||
c.msMtx.Unlock()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Collect base non-memory metrics.
|
||||
c.base.Collect(ch)
|
||||
|
||||
timer := time.NewTimer(c.msMaxWait)
|
||||
select {
|
||||
case <-done: // Our own ReadMemStats succeeded in time. Use it.
|
||||
timer.Stop() // Important for high collection frequencies to not pile up timers.
|
||||
c.msCollect(ch, ms)
|
||||
return
|
||||
case <-timer.C: // Time out, use last memstats if possible. Continue below.
|
||||
}
|
||||
c.msMtx.Lock()
|
||||
if time.Since(c.msLastTimestamp) < c.msMaxAge {
|
||||
// Last memstats are recent enough. Collect from them under the lock.
|
||||
c.msCollect(ch, c.msLast)
|
||||
c.msMtx.Unlock()
|
||||
return
|
||||
}
|
||||
// If we are here, the last memstats are too old or don't exist. We have
|
||||
// to wait until our own ReadMemStats finally completes. For that to
|
||||
// happen, we have to release the lock.
|
||||
c.msMtx.Unlock()
|
||||
<-done
|
||||
c.msCollect(ch, ms)
|
||||
}
|
||||
|
||||
func (c *goCollector) msCollect(ch chan<- Metric, ms *runtime.MemStats) {
|
||||
for _, i := range c.msMetrics {
|
||||
ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user