diff --git a/go.mod b/go.mod index 711fba5eb1f..cf1cd49d090 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/beevik/etree v1.6.0 github.com/blevesearch/bleve/v2 v2.6.0 github.com/cenkalti/backoff v2.2.1+incompatible - github.com/coreos/go-oidc/v3 v3.18.0 + github.com/coreos/go-oidc/v3 v3.19.0 github.com/cs3org/go-cs3apis v0.0.0-20241105092511-3ad35d174fc1 github.com/davidbyttow/govips/v2 v2.18.0 github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 @@ -65,7 +65,7 @@ require ( github.com/open-policy-agent/opa v1.17.1 github.com/orcaman/concurrent-map v1.0.0 github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 - github.com/owncloud/reva/v2 v2.0.0-20260618144822-5723b763a8d4 + github.com/owncloud/reva/v2 v2.0.0-20260622213237-e11912c5ad0b github.com/pkg/errors v0.9.1 github.com/pkg/xattr v0.4.12 github.com/prometheus/client_golang v1.23.2 @@ -154,7 +154,7 @@ require ( github.com/bluele/gcache v0.0.2 // indirect github.com/bombsimon/logrusr/v3 v3.1.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/ceph/go-ceph v0.39.0 // indirect + github.com/ceph/go-ceph v0.40.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cevaris/ordered_map v0.0.0-20190319150403-3adeae072e73 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect @@ -259,7 +259,7 @@ require ( github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.23 // indirect - github.com/mattn/go-sqlite3 v1.14.44 // indirect + github.com/mattn/go-sqlite3 v1.14.47 // indirect github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect github.com/miekg/dns v1.1.68 // indirect @@ -284,15 +284,15 @@ require ( github.com/olekukonko/ll v0.1.6 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect - github.com/pablodz/inotifywaitgo v0.0.9 // indirect + github.com/pablodz/inotifywaitgo v0.0.12 // indirect github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/philhofer/fwd v1.2.0 // indirect - github.com/pierrec/lz4/v4 v4.1.15 // indirect + github.com/pierrec/lz4/v4 v4.1.26 // indirect github.com/pjbgf/sha1cd v0.6.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/pquerna/cachecontrol v0.2.0 // indirect - github.com/prometheus/alertmanager v0.32.1 // indirect + github.com/prometheus/alertmanager v0.33.0 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.67.5 // indirect github.com/prometheus/procfs v0.20.1 // indirect @@ -328,9 +328,9 @@ require ( github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect github.com/yashtewari/glob-intersection v0.2.0 // indirect github.com/zeebo/xxh3 v1.1.0 // indirect - go.etcd.io/etcd/api/v3 v3.6.11 // indirect - go.etcd.io/etcd/client/pkg/v3 v3.6.11 // indirect - go.etcd.io/etcd/client/v3 v3.6.11 // indirect + go.etcd.io/etcd/api/v3 v3.6.12 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.6.12 // indirect + go.etcd.io/etcd/client/v3 v3.6.12 // indirect go.opencensus.io v0.24.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect diff --git a/go.sum b/go.sum index 39316b0130b..be4d7332402 100644 --- a/go.sum +++ b/go.sum @@ -173,6 +173,8 @@ github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F9 github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/ceph/go-ceph v0.39.0 h1:fzINuBItJqhmTtnC4/iiTY+ONtsOqV7W+B/3xTS/DsY= github.com/ceph/go-ceph v0.39.0/go.mod h1:UId58dqtDKTwnv3OY8rdpC+Ulz/AVpcvZqjXDICcd5c= +github.com/ceph/go-ceph v0.40.0 h1:Wz9WOX6i73Hz74mpwhTO9S6IyX3eFPv88VUc7FRMPRk= +github.com/ceph/go-ceph v0.40.0/go.mod h1:1oFtT/x/4y+teLsNiogdd/Kj81Gmrw6JM5w1bWnZoc4= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -192,6 +194,8 @@ github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJ github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= +github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I= +github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= @@ -653,6 +657,8 @@ github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3Ry github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= +github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo= +github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b h1:Q53idHrTuQDDHyXaxZ6pUl0I9uyD6Z6uKFK3ocX6LzI= github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b/go.mod h1:KirJrATYGbTyUwVR26xIkaipRqRcMRXBf8N5dacvGus= @@ -742,10 +748,14 @@ github.com/owncloud/reva/v2 v2.0.0-20260615095856-38834879b278 h1:C7GwyiiOiXpndV github.com/owncloud/reva/v2 v2.0.0-20260615095856-38834879b278/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U= github.com/owncloud/reva/v2 v2.0.0-20260618144822-5723b763a8d4 h1:vhEhggAcEdCnJ7AcsKQJnxx9p2deT5HrrYWJumuV5Jc= github.com/owncloud/reva/v2 v2.0.0-20260618144822-5723b763a8d4/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U= +github.com/owncloud/reva/v2 v2.0.0-20260622213237-e11912c5ad0b h1:rWZ4yV9SeA6E3RG9wVmSUm8nIg9qLUGBqKNYALj4KJ4= +github.com/owncloud/reva/v2 v2.0.0-20260622213237-e11912c5ad0b/go.mod h1:DGxAhnp9UugqZNjJfSD3rs7YhbAPWuM1+rYvz69xQeo= github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw= github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0= github.com/pablodz/inotifywaitgo v0.0.9 h1:njquRbBU7fuwIe5rEvtaniVBjwWzcpdUVptSgzFqZsw= github.com/pablodz/inotifywaitgo v0.0.9/go.mod h1:hAfx2oN+WKg8miwUKPs52trySpPignlRBRxWcXVHku0= +github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M= +github.com/pablodz/inotifywaitgo v0.0.12/go.mod h1:JWyDC6H+5oZRdUJUgKuaye+8Ph5hEs6HVzVoPKzWSGI= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= @@ -756,6 +766,8 @@ github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0= github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY= +github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU= github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -771,6 +783,8 @@ github.com/pquerna/cachecontrol v0.2.0 h1:vBXSNuE5MYP9IJ5kjsdo8uq+w41jSPgvba2DEn github.com/pquerna/cachecontrol v0.2.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI= github.com/prometheus/alertmanager v0.32.1 h1:BQ3jHXNq2A7VSD9Kh0Qx+kXbifNbHSDuKVbMmdRHHJ0= github.com/prometheus/alertmanager v0.32.1/go.mod h1:0Dy9faTtMgpVYxJVxV0o65elTxHnSRCF/7gy5BKGZiE= +github.com/prometheus/alertmanager v0.33.0 h1:AAVa3wpCsaDxisTUUPXx+1qhnA2mx0f8Cc+smpAtN7w= +github.com/prometheus/alertmanager v0.33.0/go.mod h1:V06Uc8EZ5X5wLOJRGhtXx+EE2LgrinFIADbKWMVm1RY= github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= @@ -950,10 +964,16 @@ go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= go.etcd.io/etcd/api/v3 v3.6.11 h1:XFGTgrJ8nak3kB4NgMG8t7NT+lEeuuvKQAqUHKVgkWQ= go.etcd.io/etcd/api/v3 v3.6.11/go.mod h1:HYfTh0jyh+uFgp6gMbxJteIDYY97yMuYz85Rnw6Gy9o= +go.etcd.io/etcd/api/v3 v3.6.12 h1:OLOZUKEuAA36TR48F0cIaa8FdzrWygjyfrJxXg4iDgs= +go.etcd.io/etcd/api/v3 v3.6.12/go.mod h1:p14EIQXHbuOQbVvL/WEes5uqKnxP9AgKJgpjbMVvzvE= go.etcd.io/etcd/client/pkg/v3 v3.6.11 h1:e41mp315Yn3QMGPmEzCyLsMINgJXTY/dX8kM++1csxU= go.etcd.io/etcd/client/pkg/v3 v3.6.11/go.mod h1:DysuMe/inqRyC/1tjRR6hReH/VV9Lufs27YKSKBWWJg= +go.etcd.io/etcd/client/pkg/v3 v3.6.12 h1:36zzB+pQOdHbhN+kH2iJz/K8bJn0ZLtLfPPO7jozTDo= +go.etcd.io/etcd/client/pkg/v3 v3.6.12/go.mod h1:hh2+ZXtfLzs3o6mn92ntgNPBrTJJOvXqICM5g3L3DMY= go.etcd.io/etcd/client/v3 v3.6.11 h1:LAByD96VmmeuairkvdAcE0RZnrmGz/q3ceeWePo9bwc= go.etcd.io/etcd/client/v3 v3.6.11/go.mod h1:vOTDMCo+fGPEClJqcFEFSqZ+8e7WKV7AyqJjX//HR2w= +go.etcd.io/etcd/client/v3 v3.6.12 h1:kMSP6JcPZMqSJiX+TXdUIBU/4eXEZWBAaui4VihMbIc= +go.etcd.io/etcd/client/v3 v3.6.12/go.mod h1:CMs6fJWYiZQk4ytFjd4lE1diOvvRMmtbbn/alZXd3dQ= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= diff --git a/services/webdav/pkg/service/v0/search.go b/services/webdav/pkg/service/v0/search.go index 9c979978266..86ad7d7823c 100644 --- a/services/webdav/pkg/service/v0/search.go +++ b/services/webdav/pkg/service/v0/search.go @@ -13,7 +13,6 @@ import ( merrors "go-micro.dev/v4/errors" "go-micro.dev/v4/metadata" - "github.com/owncloud/ocis/v2/ocis-pkg/mfa" searchmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/search/v0" searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" "github.com/owncloud/ocis/v2/services/webdav/pkg/constants" diff --git a/vendor/github.com/ceph/go-ceph/cephfs/admin/subvolumegroup_info.go b/vendor/github.com/ceph/go-ceph/cephfs/admin/subvolumegroup_info.go new file mode 100644 index 00000000000..8d41be858c3 --- /dev/null +++ b/vendor/github.com/ceph/go-ceph/cephfs/admin/subvolumegroup_info.go @@ -0,0 +1,50 @@ +//go:build ceph_preview + +package admin + +// SubVolumeGroupInfo reports various informational values about a subvolume group. +type SubVolumeGroupInfo struct { + Uid int `json:"uid"` + Gid int `json:"gid"` + Mode int `json:"mode"` + BytesPercent string `json:"bytes_pcent"` + BytesUsed ByteCount `json:"bytes_used"` + BytesQuota QuotaSize `json:"-"` + DataPool string `json:"data_pool"` + Atime TimeStamp `json:"atime"` + Mtime TimeStamp `json:"mtime"` + Ctime TimeStamp `json:"ctime"` + CreatedAt TimeStamp `json:"created_at"` + MonAddrs []string `json:"mon_addrs"` +} + +type subVolumeGroupInfoWrapper struct { + SubVolumeGroupInfo + VBytesQuota *quotaSizePlaceholder `json:"bytes_quota"` +} + +func parseSubVolumeGroupInfo(res response) (*SubVolumeGroupInfo, error) { + var info subVolumeGroupInfoWrapper + if err := res.NoStatus().Unmarshal(&info).End(); err != nil { + return nil, err + } + if info.VBytesQuota != nil { + info.BytesQuota = info.VBytesQuota.Value + } + return &info.SubVolumeGroupInfo, nil +} + +// SubVolumeGroupInfo returns information about the specified subvolume group. +// +// Similar To: +// +// ceph fs subvolumegroup info +func (fsa *FSAdmin) SubVolumeGroupInfo(volume, name string) (*SubVolumeGroupInfo, error) { + res := fsa.marshalMgrCommand(map[string]string{ + "prefix": "fs subvolumegroup info", + "vol_name": volume, + "group_name": name, + "format": "json", + }) + return parseSubVolumeGroupInfo(res) +} diff --git a/vendor/github.com/ceph/go-ceph/cephfs/block_diff.go b/vendor/github.com/ceph/go-ceph/cephfs/block_diff.go index b41dc5a7647..bf6b51b6957 100644 --- a/vendor/github.com/ceph/go-ceph/cephfs/block_diff.go +++ b/vendor/github.com/ceph/go-ceph/cephfs/block_diff.go @@ -1,5 +1,3 @@ -//go:build ceph_preview - package cephfs /* diff --git a/vendor/github.com/ceph/go-ceph/cephfs/snap_diff.go b/vendor/github.com/ceph/go-ceph/cephfs/snap_diff.go index 545dabb41a6..0f9608ee67b 100644 --- a/vendor/github.com/ceph/go-ceph/cephfs/snap_diff.go +++ b/vendor/github.com/ceph/go-ceph/cephfs/snap_diff.go @@ -147,13 +147,22 @@ func OpenSnapDiff(config SnapDiffConfig) (*SnapDiffInfo, error) { rawCephSnapDiffInfo := &C._ceph_snapdiff_info{} + cRootPath := C.CString(config.RootPath) + defer C.free(unsafe.Pointer(cRootPath)) + cRelPath := C.CString(config.RelPath) + defer C.free(unsafe.Pointer(cRelPath)) + cSnap1 := C.CString(config.Snap1) + defer C.free(unsafe.Pointer(cSnap1)) + cSnap2 := C.CString(config.Snap2) + defer C.free(unsafe.Pointer(cSnap2)) + ret := C.open_snapdiff_dlsym( cephOpenSnapDiff, config.CMount.mount, - C.CString(config.RootPath), - C.CString(config.RelPath), - C.CString(config.Snap1), - C.CString(config.Snap2), + cRootPath, + cRelPath, + cSnap1, + cSnap2, rawCephSnapDiffInfo) if ret != 0 { diff --git a/vendor/github.com/ceph/go-ceph/rados/ioctx_checksum.go b/vendor/github.com/ceph/go-ceph/rados/ioctx_checksum.go new file mode 100644 index 00000000000..433100cdfbd --- /dev/null +++ b/vendor/github.com/ceph/go-ceph/rados/ioctx_checksum.go @@ -0,0 +1,86 @@ +//go:build ceph_preview + +package rados + +/* +#cgo LDFLAGS: -lrados +#include +#include +*/ +import "C" + +import "unsafe" + +// Checksum calculates the checksum of the given object data, using one of the supported checksum algorithms. +// +// Implements: +// +// int rados_checksum(rados_ioctx_t io, +// const char *oid, +// rados_checksum_type_t type, +// const char *init_value, +// size_t init_value_len, +// size_t len, +// uint64_t off, +// size_t chunk_size, +// char *pchecksum, +// size_t checksum_len); +func (ioctx *IOContext) Checksum(oid string, checksumType ChecksumType, dst []byte, opts *ChecksumOptions) error { + // apply defaults + if opts == nil { + opts = &ChecksumOptions{} + } + if opts.InitValue == nil { + initLen := 4 + if checksumType == ChecksumTypeXXHash64 { + initLen = 8 + } + opts.InitValue = make([]byte, initLen) + } + + // call library + coid := C.CString(oid) + defer C.free(unsafe.Pointer(coid)) + + return getError(C.rados_checksum( + ioctx.ioctx, + coid, + C.rados_checksum_type_t(checksumType), + (*C.char)(unsafe.Pointer(&opts.InitValue[0])), + C.size_t(len(opts.InitValue)), + C.size_t(opts.Len), + C.uint64_t(opts.Off), + C.size_t(opts.ChunkSize), + (*C.char)(unsafe.Pointer(&dst[0])), + C.size_t(len(dst)), + )) +} + +// ChecksumType indicates checksum algorithm types supported by the IOContext.Checksum method. +// Equivalent to the rados_checksum_type_t enum. +type ChecksumType uint32 + +const ( + // ChecksumTypeXXHash32 produces an encoded le32 checksum of the given object. + ChecksumTypeXXHash32 = ChecksumType(C.LIBRADOS_CHECKSUM_TYPE_XXHASH32) + // ChecksumTypeXXHash64 produces an encoded le64 checksum of the given object. + ChecksumTypeXXHash64 = ChecksumType(C.LIBRADOS_CHECKSUM_TYPE_XXHASH64) + // ChecksumTypeCRC32C produces an encoded le32 checksum of the given object. + ChecksumTypeCRC32C = ChecksumType(C.LIBRADOS_CHECKSUM_TYPE_CRC32C) +) + +// ChecksumOptions exposes non-required parameters for the Checksum method. +type ChecksumOptions struct { + // Off sets the object offset to start checksumming in the object. + // By default, the entire object will be checksummed. + Off uint64 + // Len sets the the number of bytes to checksum in the object. + // By default, the entire object will be checksummed. + Len uint64 + // ChunkSize sets the length-aligned chunk size for the checksum calculation. + // By default, the entire object will be checksummed as a single chunk. + ChunkSize uint64 + // InitValue sets the initial value for the checksum calculation. + // By default, the initial value will be a zeroed-out byte slice. + InitValue []byte +} diff --git a/vendor/github.com/coreos/go-oidc/v3/oidc/jwks.go b/vendor/github.com/coreos/go-oidc/v3/oidc/jwks.go index c5e4d787c8f..d892d54e61d 100644 --- a/vendor/github.com/coreos/go-oidc/v3/oidc/jwks.go +++ b/vendor/github.com/coreos/go-oidc/v3/oidc/jwks.go @@ -238,6 +238,7 @@ func (r *RemoteKeySet) updateKeys() ([]jose.JSONWebKey, error) { if err != nil { return nil, fmt.Errorf("oidc: can't create request: %v", err) } + req.Header.Set("Cache-Control", "no-cache") resp, err := doRequest(r.ctx, req) if err != nil { diff --git a/vendor/github.com/coreos/go-oidc/v3/oidc/logout.go b/vendor/github.com/coreos/go-oidc/v3/oidc/logout.go new file mode 100644 index 00000000000..2edeaa2441f --- /dev/null +++ b/vendor/github.com/coreos/go-oidc/v3/oidc/logout.go @@ -0,0 +1,187 @@ +package oidc + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" +) + +// LogoutToken represents a verified token from a Back-Channel Logout. Use +// [IDTokenVerifier.VerifyLogout] within a POST handler to receive and validate +// a token. +// +// See the ./example/logout at the top-level of this repo for a full example +// application. +type LogoutToken struct { + // The required token ID claim ("jti"). When processing this token for + // logout, applications should validate that no recent token with the same + // value has been processed. + TokenID string + // The unique identifier of the user that this logout token is for. This + // will match the subject value of the ID Token. + // + // If not set, SessionID will be. + Subject string + + // The "iss" claim. This is validated against the provider URL unless + // explicitly skipped through SkipIssuerCheck. + Issuer string + // The Client ID this logout token is for. Validated against the config + // unless SkipClientIDCheck is provided. + Audience []string + // When this token was issued. + IssuedAt time.Time + // When this token expires. Validated unless SkipExpiryCheck is provided. + Expiry time.Time + // Optional session ID claim ("sid"). + // + // The exact semantics of session IDs very between identity providers. Use + // your provider's documentation to determine what this correlates to and + // how it should be handled. + SessionID string + + claims []byte +} + +// Claims unmarshals the raw JSON payload of the Logout Token into a provided +// struct. This can be used to access field not exposed by the LogoutToken +// fields. +// +// logoutToken, err := idTokenVerifier.VerifyLogout(ctx, rawLogoutToken) +// if err != nil{ +// // ... +// } +// var claims struct { +// TraceID string `json:"trace_id"` +// } +// if err := logoutToken.Claims(&claims); err != nil { +// // ... +// } +func (l *LogoutToken) Claims(v any) error { + if l.claims == nil { + return errors.New("oidc: claims not set") + } + return json.Unmarshal(l.claims, v) +} + +// https://openid.net/specs/openid-connect-backchannel-1_0.html#LogoutToken +type logoutTokenJSON struct { + Issuer string `json:"iss"` + Subject string `json:"sub"` + Audience audience `json:"aud"` + Expiry jsonTime `json:"exp"` + IssuedAt jsonTime `json:"iat"` + JTI string `json:"jti"` + Events struct { + Logout json.RawMessage `json:"http://schemas.openid.net/event/backchannel-logout"` + } + SessionID string `json:"sid"` + // Nonce is parsed as a raw message so its mere presence can be detected. + // The spec requires logout tokens to not contain a nonce claim, regardless + // of its value. + Nonce json.RawMessage `json:"nonce"` +} + +// VerifyLogout validates a back-channel logout token. Logout tokens are +// received by the relying party (this package) from the identity provider at a +// preconfigured "backchannel_logout_uri" through a POST. Then on certain +// events, such as RP-Initiated Logout, the identity provider will send a signed +// token indicating that sessions for a specific user should be terminated. +// +// To support back-channel logout within your app, register a POST endpoint and +// verify the token: +// +// oidcConfig := &oidc.Config{ +// ClientID: clientID, +// } +// verifier := provider.Verifier(oidcConfig) +// +// mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Reequest) { +// rawLogoutToken := r.PostFormValue("logout_token") +// if rawLogoutToken == "" { +// // ... +// } +// logoutToken, err := verifier.VerifyLogout(r.Context(), rawLogoutToken) +// if err != nil { +// // ... +// } +// // Use fields in the logoutToken to determine what sessions to +// // terminate. +// +// }) +// +// Back-channel logout spec: https://openid.net/specs/openid-connect-backchannel-1_0.html +// +// RP-initiated logout spec: https://openid.net/specs/openid-connect-rpinitiated-1_0.html +func (v *IDTokenVerifier) VerifyLogout(ctx context.Context, rawLogoutToken string) (*LogoutToken, error) { + payload, _, err := v.verifyJWT(ctx, rawLogoutToken) + if err != nil { + return nil, err + } + var logoutToken logoutTokenJSON + if err := json.Unmarshal(payload, &logoutToken); err != nil { + return nil, fmt.Errorf("oidc: parsing logout token payload: %v", err) + } + + if len(logoutToken.Events.Logout) == 0 { + return nil, fmt.Errorf("oidc: logout token missing required http://schemas.openid.net/event/backchannel-logout event") + } + + // A logout token MUST NOT contain a nonce claim. This prevents an ID token + // from being replayed as a logout token. + if len(logoutToken.Nonce) != 0 { + return nil, fmt.Errorf("oidc: logout token must not contain a 'nonce' claim") + } + + t := &LogoutToken{ + Issuer: logoutToken.Issuer, + Subject: logoutToken.Subject, + Audience: logoutToken.Audience, + IssuedAt: time.Time(logoutToken.IssuedAt), + Expiry: time.Time(logoutToken.Expiry), + SessionID: logoutToken.SessionID, + TokenID: logoutToken.JTI, + claims: payload, + } + if t.TokenID == "" { + return nil, fmt.Errorf("oidc: logout token missing required claim 'jti'") + } + if t.Expiry.IsZero() { + return nil, fmt.Errorf("oidc: logout token must contain an 'exp' claim") + } + + // A logout token MUST contain a 'sub' claim, a 'sid' claim, or both. + if t.Subject == "" && t.SessionID == "" { + return nil, fmt.Errorf("oidc: logout token must contain a 'sub' claim, a 'sid' claim, or both") + } + + if !v.config.SkipIssuerCheck && t.Issuer != v.issuer { + return nil, fmt.Errorf("oidc: logout token issued by a different provider, expected %q, got %q", v.issuer, t.Issuer) + } + + if !v.config.SkipClientIDCheck { + if v.config.ClientID != "" { + if !contains(t.Audience, v.config.ClientID) { + return nil, fmt.Errorf("oidc: expected logout token audience %q got %q", v.config.ClientID, t.Audience) + } + } else { + return nil, fmt.Errorf("oidc: invalid configuration, clientID must be provided or SkipClientIDCheck must be set") + } + } + + // If a SkipExpiryCheck is false, make sure token is not expired. + if !v.config.SkipExpiryCheck { + now := time.Now + if v.config.Now != nil { + now = v.config.Now + } + nowTime := now() + + if t.Expiry.Before(nowTime) { + return nil, &TokenExpiredError{Expiry: t.Expiry} + } + } + return t, nil +} diff --git a/vendor/github.com/coreos/go-oidc/v3/oidc/verify.go b/vendor/github.com/coreos/go-oidc/v3/oidc/verify.go index a8bf107d4a6..895721e2b94 100644 --- a/vendor/github.com/coreos/go-oidc/v3/oidc/verify.go +++ b/vendor/github.com/coreos/go-oidc/v3/oidc/verify.go @@ -17,9 +17,10 @@ const ( issuerGoogleAccountsNoScheme = "accounts.google.com" ) -// TokenExpiredError indicates that Verify failed because the token was expired. This -// error does NOT indicate that the token is not also invalid for other reasons. Other -// checks might have failed if the expiration check had not failed. +// TokenExpiredError indicates that Verify or VerifyLogout failed because the +// token was expired. This error does NOT indicate that the token is not also +// invalid for other reasons. Other checks might have failed if the expiration +// check had not failed. type TokenExpiredError struct { // Expiry is the time when the token expired. Expiry time.Time @@ -44,7 +45,7 @@ type KeySet interface { VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) } -// IDTokenVerifier provides verification for ID Tokens. +// IDTokenVerifier provides verification for ID Tokens and Logout Tokens. type IDTokenVerifier struct { keySet KeySet config *Config @@ -203,48 +204,9 @@ func resolveDistributedClaim(ctx context.Context, verifier *IDTokenVerifier, src // // token, err := verifier.Verify(ctx, rawIDToken) func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDToken, error) { - var supportedSigAlgs []jose.SignatureAlgorithm - for _, alg := range v.config.SupportedSigningAlgs { - supportedSigAlgs = append(supportedSigAlgs, jose.SignatureAlgorithm(alg)) - } - if len(supportedSigAlgs) == 0 { - // If no algorithms were specified by both the config and discovery, default - // to the one mandatory algorithm "RS256". - supportedSigAlgs = []jose.SignatureAlgorithm{jose.RS256} - } - if v.config.InsecureSkipSignatureCheck { - // "none" is a required value to even parse a JWT with the "none" algorithm - // using go-jose. - supportedSigAlgs = append(supportedSigAlgs, "none") - } - - // Parse and verify the signature first. This at least forces the user to have - // a valid, signed ID token before we do any other processing. - jws, err := jose.ParseSigned(rawIDToken, supportedSigAlgs) + payload, sig, err := v.verifyJWT(ctx, rawIDToken) if err != nil { - return nil, fmt.Errorf("oidc: malformed jwt: %v", err) - } - switch len(jws.Signatures) { - case 0: - return nil, fmt.Errorf("oidc: id token not signed") - case 1: - default: - return nil, fmt.Errorf("oidc: multiple signatures on id token not supported") - } - sig := jws.Signatures[0] - - var payload []byte - if v.config.InsecureSkipSignatureCheck { - // Yolo mode. - payload = jws.UnsafePayloadWithoutVerification() - } else { - // The JWT is attached here for the happy path to avoid the verifier from - // having to parse the JWT twice. - ctx = context.WithValue(ctx, parsedJWTKey, jws) - payload, err = v.keySet.VerifySignature(ctx, rawIDToken) - if err != nil { - return nil, fmt.Errorf("failed to verify signature: %v", err) - } + return nil, err } var token idToken if err := json.Unmarshal(payload, &token); err != nil { @@ -336,3 +298,50 @@ func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDTok func Nonce(nonce string) oauth2.AuthCodeOption { return oauth2.SetAuthURLParam("nonce", nonce) } + +func (v *IDTokenVerifier) verifyJWT(ctx context.Context, rawIDToken string) ([]byte, jose.Signature, error) { + var supportedSigAlgs []jose.SignatureAlgorithm + for _, alg := range v.config.SupportedSigningAlgs { + supportedSigAlgs = append(supportedSigAlgs, jose.SignatureAlgorithm(alg)) + } + if len(supportedSigAlgs) == 0 { + // If no algorithms were specified by both the config and discovery, default + // to the one mandatory algorithm "RS256". + supportedSigAlgs = []jose.SignatureAlgorithm{jose.RS256} + } + if v.config.InsecureSkipSignatureCheck { + // "none" is a required value to even parse a JWT with the "none" algorithm + // using go-jose. + supportedSigAlgs = append(supportedSigAlgs, "none") + } + + // Parse and verify the signature first. This at least forces the user to have + // a valid, signed ID token before we do any other processing. + jws, err := jose.ParseSigned(rawIDToken, supportedSigAlgs) + if err != nil { + return nil, jose.Signature{}, fmt.Errorf("oidc: malformed jwt: %v", err) + } + switch len(jws.Signatures) { + case 0: + return nil, jose.Signature{}, fmt.Errorf("oidc: id token not signed") + case 1: + default: + return nil, jose.Signature{}, fmt.Errorf("oidc: multiple signatures on id token not supported") + } + sig := jws.Signatures[0] + + var payload []byte + if v.config.InsecureSkipSignatureCheck { + // Yolo mode. + payload = jws.UnsafePayloadWithoutVerification() + } else { + // The JWT is attached here for the happy path to avoid the verifier from + // having to parse the JWT twice. + ctx = context.WithValue(ctx, parsedJWTKey, jws) + payload, err = v.keySet.VerifySignature(ctx, rawIDToken) + if err != nil { + return nil, jose.Signature{}, fmt.Errorf("failed to verify signature: %v", err) + } + } + return payload, sig, nil +} diff --git a/vendor/github.com/mattn/go-sqlite3/README.md b/vendor/github.com/mattn/go-sqlite3/README.md index aaec188b293..4fd391118e5 100644 --- a/vendor/github.com/mattn/go-sqlite3/README.md +++ b/vendor/github.com/mattn/go-sqlite3/README.md @@ -9,8 +9,6 @@ go-sqlite3 Latest stable version is v1.14 or later, not v2. -~~**NOTE:** The increase to v2 was an accident. There were no major changes or features.~~ - # Description A sqlite3 driver that conforms to the built-in database/sql interface. @@ -182,6 +180,7 @@ go build -tags "icu json1 fts5 secure_delete" | Tracing / Debug | sqlite_trace | Activate trace functions | | User Authentication | sqlite_userauth | SQLite User Authentication see [User Authentication](#user-authentication) for more information. | | Virtual Tables | sqlite_vtable | SQLite Virtual Tables see [SQLite Official VTABLE Documentation](https://www.sqlite.org/vtab.html) for more information, and a [full example here](https://github.com/mattn/go-sqlite3/tree/master/_example/vtable) | +| The DBSTAT Virtual Table | sqlite_dbstat | The DBSTAT virtual table is a read-only virtual table that returns information about the amount of disk space used to store the content of an SQLite database. See [SQLite Official Documentation](https://www.sqlite.org/dbstat.html) for more information. | # Compilation diff --git a/vendor/github.com/mattn/go-sqlite3/callback.go b/vendor/github.com/mattn/go-sqlite3/callback.go index 0c518fa2c1b..293d26dba02 100644 --- a/vendor/github.com/mattn/go-sqlite3/callback.go +++ b/vendor/github.com/mattn/go-sqlite3/callback.go @@ -18,7 +18,7 @@ package sqlite3 #endif #include -void _sqlite3_result_text(sqlite3_context* ctx, const char* s); +void _sqlite3_result_text(sqlite3_context* ctx, const char* s, int n); void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l); */ import "C" @@ -29,6 +29,7 @@ import ( "math" "reflect" "sync" + "sync/atomic" "unsafe" ) @@ -104,24 +105,26 @@ type handleVal struct { } var handleLock sync.Mutex -var handleVals = make(map[unsafe.Pointer]handleVal) +var handleVals atomic.Value // stores map[unsafe.Pointer]handleVal func newHandle(db *SQLiteConn, v any) unsafe.Pointer { - handleLock.Lock() - defer handleLock.Unlock() val := handleVal{db: db, val: v} var p unsafe.Pointer = C.malloc(C.size_t(1)) if p == nil { panic("can't allocate 'cgo-pointer hack index pointer': ptr == nil") } - handleVals[p] = val + + handleLock.Lock() + defer handleLock.Unlock() + + next := cloneHandleVals(len(loadHandleVals()) + 1) + next[p] = val + handleVals.Store(next) return p } func lookupHandleVal(handle unsafe.Pointer) handleVal { - handleLock.Lock() - defer handleLock.Unlock() - return handleVals[handle] + return loadHandleVals()[handle] } func lookupHandle(handle unsafe.Pointer) any { @@ -131,12 +134,34 @@ func lookupHandle(handle unsafe.Pointer) any { func deleteHandles(db *SQLiteConn) { handleLock.Lock() defer handleLock.Unlock() - for handle, val := range handleVals { - if val.db == db { - delete(handleVals, handle) - C.free(handle) - } + + current := loadHandleVals() + if len(current) == 0 { + return } + + next := make(map[unsafe.Pointer]handleVal, len(current)) + for handle, val := range current { + if val.db == db { + C.free(handle) + continue + } + next[handle] = val + } + handleVals.Store(next) +} + +func loadHandleVals() map[unsafe.Pointer]handleVal { + m, _ := handleVals.Load().(map[unsafe.Pointer]handleVal) + return m +} + +func cloneHandleVals(size int) map[unsafe.Pointer]handleVal { + next := make(map[unsafe.Pointer]handleVal, size) + for handle, val := range loadHandleVals() { + next[handle] = val + } + return next } // This is only here so that tests can refer to it. @@ -204,12 +229,13 @@ func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) { func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) { switch C.sqlite3_value_type(v) { case C.SQLITE_BLOB: - l := C.sqlite3_value_bytes(v) p := (*C.char)(C.sqlite3_value_blob(v)) + l := C.sqlite3_value_bytes(v) return reflect.ValueOf(C.GoStringN(p, l)), nil case C.SQLITE_TEXT: c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v))) - return reflect.ValueOf(C.GoString(c)), nil + l := C.sqlite3_value_bytes(v) + return reflect.ValueOf(C.GoStringN(c, l)), nil default: return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT") } @@ -336,6 +362,10 @@ func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error { C.sqlite3_result_null(ctx) } else { bs := i.([]byte) + if i64 && len(bs) > math.MaxInt32 { + C.sqlite3_result_error_toobig(ctx) + return nil + } C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs))) } return nil @@ -345,8 +375,13 @@ func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error { if v.Type().Kind() != reflect.String { return fmt.Errorf("cannot convert %s to TEXT", v.Type()) } - cstr := C.CString(v.Interface().(string)) - C._sqlite3_result_text(ctx, cstr) + s := v.Interface().(string) + if i64 && len(s) > math.MaxInt32 { + C.sqlite3_result_error_toobig(ctx) + return nil + } + cstr := C.CString(s) + C._sqlite3_result_text(ctx, cstr, C.int(len(s))) return nil } diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c index 97f3008098b..28c91060042 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.c @@ -1,7 +1,7 @@ #ifndef USE_LIBSQLITE3 /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite -** version 3.53.0. By combining all the individual C code files into this +** version 3.53.2. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a single translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements @@ -19,7 +19,7 @@ ** separate file. This file contains only code for the core SQLite library. ** ** The content in this amalgamation comes from Fossil check-in -** 4525003a53a7fc63ca75c59b22c79608659c with changes in files: +** d6e03d8c777cfa2d35e3b60d8ec3e0187f3e with changes in files: ** ** */ @@ -468,12 +468,12 @@ extern "C" { ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.53.0" -#define SQLITE_VERSION_NUMBER 3053000 -#define SQLITE_SOURCE_ID "2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b" -#define SQLITE_SCM_BRANCH "trunk" -#define SQLITE_SCM_TAGS "release major-release version-3.53.0" -#define SQLITE_SCM_DATETIME "2026-04-09T11:41:38.498Z" +#define SQLITE_VERSION "3.53.2" +#define SQLITE_VERSION_NUMBER 3053002 +#define SQLITE_SOURCE_ID "2026-06-03 19:12:13 d6e03d8c777cfa2d35e3b60d8ec3e0187f3e9f99d8e2ee9cac695fd6fcdf1a24" +#define SQLITE_SCM_BRANCH "branch-3.53" +#define SQLITE_SCM_TAGS "release version-3.53.2" +#define SQLITE_SCM_DATETIME "2026-06-03T19:12:13.350Z" /* ** CAPI3REF: Run-Time Library Version Numbers @@ -13175,11 +13175,23 @@ SQLITE_API int sqlite3changeset_apply_v3( ** database behave as if they were declared with "ON UPDATE NO ACTION ON ** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL ** or SET DEFAULT. +** +**
SQLITE_CHANGESETAPPLY_NOUPDATELOOP
+** Sometimes, a changeset contains two or more update statements such that +** although after applying all updates the database will contain no +** constraint violations, no single update can be applied before the others. +** The simplest example of this is a pair of UPDATEs that have "swapped" +** two column values with a UNIQUE constraint. +**

+** Usually, sqlite3changeset_apply() and similar functions work hard to try +** to find a way to apply such a changeset. However, if this flag is set, +** then all such updates are considered CONSTRAINT conflicts. */ #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 #define SQLITE_CHANGESETAPPLY_INVERT 0x0002 #define SQLITE_CHANGESETAPPLY_IGNORENOOP 0x0004 #define SQLITE_CHANGESETAPPLY_FKNOACTION 0x0008 +#define SQLITE_CHANGESETAPPLY_NOUPDATELOOP 0x0010 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -22449,7 +22461,15 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void); SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*); SQLITE_PRIVATE void sqlite3AlterDropConstraint(Parse*,SrcList*,Token*,Token*); -SQLITE_PRIVATE void sqlite3AlterAddConstraint(Parse*,SrcList*,Token*,Token*,const char*,int); +SQLITE_PRIVATE void sqlite3AlterAddConstraint( + Parse *pParse, /* Parse context */ + SrcList *pSrc, /* Table to add constraint to */ + Token *pFirst, /* First token of new constraint */ + Token *pName, /* Name of new constraint. NULL if name omitted. */ + const char *zExpr, /* Text of CHECK expression */ + int nExpr, /* Size of pExpr in bytes */ + Expr *pExpr /* The parsed CHECK expression */ +); SQLITE_PRIVATE void sqlite3AlterSetNotNull(Parse*, SrcList*, Token*, Token*); SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *); SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); @@ -32514,7 +32534,7 @@ static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){ sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG); return 0; } - z = sqlite3DbMallocRaw(pAccum->db, n); + z = sqlite3_malloc(n); if( z==0 ){ sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM); } @@ -32972,11 +32992,27 @@ SQLITE_API void sqlite3_str_vappendf( szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+10; if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3; - if( sqlite3StrAccumEnlargeIfNeeded(pAccum, szBufNeeded) ){ - width = length = 0; - break; + if( szBufNeeded + pAccum->nChar >= pAccum->nAlloc ){ + if( pAccum->mxAlloc==0 && pAccum->accError==0 ){ + /* Unable to allocate space in pAccum, perhaps because it + ** is coming from sqlite3_snprintf() or similar. We'll have + ** to render into temporary space and the memcpy() it over. */ + bufpt = sqlite3_malloc(szBufNeeded); + if( bufpt==0 ){ + sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM); + return; + } + zExtra = bufpt; + }else if( sqlite3StrAccumEnlarge(pAccum, szBufNeeded)zText + pAccum->nChar; + } + }else{ + bufpt = pAccum->zText + pAccum->nChar; } - bufpt = zOut = pAccum->zText + pAccum->nChar; + zOut = bufpt; flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; /* The sign in front of the number */ @@ -33077,14 +33113,22 @@ SQLITE_API void sqlite3_str_vappendf( } length = width; } - pAccum->nChar += length; - zOut[length] = 0; - /* Floating point conversions render directly into the output - ** buffer. Hence, don't just break out of the switch(). Bypass the - ** output buffer writing that occurs after the switch() by continuing - ** to the next character in the format string. */ - continue; + if( zExtra==0 ){ + /* The result is being rendered directory into pAccum. This + ** is the command and fast case */ + pAccum->nChar += length; + zOut[length] = 0; + continue; + }else{ + /* We were unable to render directly into pAccum because we + ** couldn't allocate sufficient memory. We need to memcpy() + ** the rendering (or some prefix thereof) into the output + ** buffer. */ + bufpt[0] = 0; + bufpt = zExtra; + break; + } } case etSIZE: if( !bArgList ){ @@ -33131,7 +33175,7 @@ SQLITE_API void sqlite3_str_vappendf( if( sqlite3StrAccumEnlargeIfNeeded(pAccum, nCopyBytes) ){ break; } - sqlite3_str_append(pAccum, + sqlite3_str_append(pAccum, &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes); precision -= nPrior; nPrior *= 2; @@ -33234,8 +33278,8 @@ SQLITE_API void sqlite3_str_vappendf( ** all control characters, and for backslash itself. ** For %#Q, do the same but only if there is at least ** one control character. */ - u32 nBack = 0; - u32 nCtrl = 0; + i64 nBack = 0; + i64 nCtrl = 0; for(k=0; k32))) +#define SQLITE_USE_UINT128 +#endif + /* ** Two inputs are multiplied to get a 128-bit result. Write the ** lower 64-bits of the result into *pLo, and return the high-order ** 64 bits. */ static u64 sqlite3Multiply128(u64 a, u64 b, u64 *pLo){ -#if (defined(__GNUC__) || defined(__clang__)) \ - && (defined(__x86_64__) || defined(__aarch64__) || defined(__riscv)) \ - && !defined(SQLITE_DISABLE_INTRINSIC) +#if defined(SQLITE_USE_UINT128) __uint128_t r = (__uint128_t)a * b; *pLo = (u64)r; return (u64)(r>>64); @@ -36835,9 +36884,7 @@ static u64 sqlite3Multiply128(u64 a, u64 b, u64 *pLo){ ** The lower 64 bits of A*B are discarded. */ static u64 sqlite3Multiply160(u64 a, u32 aLo, u64 b, u32 *pLo){ -#if (defined(__GNUC__) || defined(__clang__)) \ - && (defined(__x86_64__) || defined(__aarch64__) || defined(__riscv)) \ - && !defined(SQLITE_DISABLE_INTRINSIC) +#if defined(SQLITE_USE_UINT128) __uint128_t r = (__uint128_t)a * b; r += ((__uint128_t)aLo * b) >> 32; *pLo = (r>>32)&0xffffffff; @@ -36875,6 +36922,8 @@ static u64 sqlite3Multiply160(u64 a, u32 aLo, u64 b, u32 *pLo){ #endif } +#undef SQLITE_USE_UINT128 + /* ** Return a u64 with the N-th bit set. */ @@ -45279,9 +45328,9 @@ static int unixShmMap( nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; if( pShmNode->nRegionszRegion = szRegion; @@ -45312,7 +45361,7 @@ static int unixShmMap( */ else{ static const int pgsz = 4096; - int iPg; + i64 iPg; /* Write to the last byte of each newly allocated or extended page */ assert( (nByte % pgsz)==0 ); @@ -45338,8 +45387,8 @@ static int unixShmMap( } pShmNode->apRegion = apNew; while( pShmNode->nRegionhShm>=0 ){ pMem = osMmap(0, nMap, @@ -53313,7 +53362,7 @@ static int winShmMap( if( pShmNode->nRegion<=iRegion ){ HANDLE hShared = pShmNode->hSharedShm; struct ShmRegion *apNew; /* New aRegion[] array */ - int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ + i64 nByte = ((i64)iRegion+1)*(i64)szRegion; /* Minimum file size */ sqlite3_int64 sz; /* Current size of wal-index file */ pShmNode->szRegion = szRegion; @@ -53344,7 +53393,7 @@ static int winShmMap( /* Map the requested memory region into this processes address space. */ apNew = (struct ShmRegion*)sqlite3_realloc64( - pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) + pShmNode->aRegion, ((i64)iRegion+1)*sizeof(apNew[0]) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; @@ -53366,15 +53415,14 @@ static int winShmMap( #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA hMap = osCreateFileMappingA(hShared, NULL, protect, 0, nByte, NULL); #endif - - OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", + OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%lld, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, nByte, hMap ? "ok" : "failed")); if( hMap ){ - int iOffset = pShmNode->nRegion*szRegion; + i64 iOffset = pShmNode->nRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; pMap = osMapViewOfFile(hMap, flags, - 0, iOffset - iOffsetShift, szRegion + iOffsetShift + 0, iOffset - iOffsetShift, (i64)szRegion + iOffsetShift ); OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, iOffset, @@ -53396,7 +53444,7 @@ static int winShmMap( shmpage_out: if( pShmNode->nRegion>iRegion ){ - int iOffset = iRegion*szRegion; + i64 iOffset = (i64)iRegion*(i64)szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; char *p = (char *)pShmNode->aRegion[iRegion].pMap; *pp = (void *)&p[iOffsetShift]; @@ -56109,10 +56157,10 @@ SQLITE_API int sqlite3_deserialize( if( rc ) goto end_deserialize; db->init.iDb = (u8)iDb; db->init.reopenMemdb = 1; - rc = sqlite3_step(pStmt); + sqlite3_step(pStmt); db->init.reopenMemdb = 0; - if( rc!=SQLITE_DONE ){ - rc = SQLITE_ERROR; + rc = sqlite3_finalize(pStmt); + if( rc!=SQLITE_OK ){ goto end_deserialize; } p = memdbFromDbSchema(db, zSchema); @@ -56133,7 +56181,6 @@ SQLITE_API int sqlite3_deserialize( } end_deserialize: - sqlite3_finalize(pStmt); if( pData && (mFlags & SQLITE_DESERIALIZE_FREEONCLOSE)!=0 ){ sqlite3_free(pData); } @@ -62125,7 +62172,7 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){ if( rc!=SQLITE_OK ) goto delsuper_out; nSuperPtr = 1 + (i64)pVfs->mxPathname; assert( nSuperJournal>=0 && nSuperPtr>0 ); - zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2); + zFree = sqlite3Malloc(4 + nSuperJournal + 2 + nSuperPtr + 2); if( !zFree ){ rc = SQLITE_NOMEM_BKPT; goto delsuper_out; @@ -62386,10 +62433,10 @@ static int pager_playback(Pager *pPager, int isHot){ ** ** TODO: Technically the following is an error because it assumes that ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that - ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, + ** ((pPager->pageSize+8) >= pPager->pVfs->mxPathname+1). Using os_unix.c, ** mxPathname is 512, which is the same as the minimum allowable value - ** for pageSize. - */ + ** for pageSize, and so this assumption holds. But it might not for some + ** custom VFS. */ zSuper = pPager->pTmpSpace; rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname); if( rc==SQLITE_OK && zSuper[0] ){ @@ -78279,7 +78326,9 @@ static int accessPayload( ** means "not yet known" (the cache is lazily populated). */ if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ - int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + i64 nOvfl = pCur->info.nPayload; + testcase( nOvfl - pCur->info.nLocal + ovflSize - 1 > 0xffffffffU ); + nOvfl = (nOvfl - pCur->info.nLocal + ovflSize-1)/ovflSize; if( pCur->aOverflow==0 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) ){ @@ -78384,6 +78433,12 @@ static int accessPayload( (eOp==0 ? PAGER_GET_READONLY : 0) ); if( rc==SQLITE_OK ){ + if( eOp!=0 + && (sqlite3PagerPageRefcount(pDbPage)!=1 + || NEVER(((MemPage*)sqlite3PagerGetExtra(pDbPage))->isInit)) ){ + sqlite3PagerUnref(pDbPage); + return SQLITE_CORRUPT_PAGE(pPage); + } aPayload = sqlite3PagerGetData(pDbPage); nextPage = get4byte(aPayload); rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); @@ -111072,6 +111127,7 @@ static int lookupName( pExpr->op = TK_FUNCTION; pExpr->u.zToken = "coalesce"; pExpr->x.pList = pFJMatch; + pExpr->affExpr = SQLITE_AFF_DEFER; cnt = 1; goto lookupname_end; }else{ @@ -111240,6 +111296,26 @@ static int exprProbability(Expr *p){ return (int)(r*134217728.0); } +/* +** Set the EP_SubtArg property on every expression inside of +** pList. If any subexpression is actually a subquery, then +** also set the EP_SubtArg property on the first result-set +** column of that subquery. +*/ +static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){ + int nn, ii; + nn = pList ? pList->nExpr : 0; + for(ii=0; iia[ii].pExpr; + ExprSetProperty(pExpr, EP_SubtArg); + if( pExpr->op==TK_SELECT ){ + assert( ExprUseXSelect(pExpr) ); + assert( pExpr->x.pSelect!=0 ); + resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList); + } + } +} + /* ** This routine is callback for sqlite3WalkExpr(). ** @@ -111484,10 +111560,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ if( (pDef->funcFlags & SQLITE_SUBTYPE) || ExprHasProperty(pExpr, EP_SubtArg) ){ - int ii; - for(ii=0; iia[ii].pExpr, EP_SubtArg); - } + resolveSetExprSubtypeArg(pList); } if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ @@ -116882,7 +116955,16 @@ static void sqlite3ExprCodeIN( CollSeq *pColl; int r3 = sqlite3GetTempReg(pParse); p = sqlite3VectorFieldSubexpr(pLeft, i); - pColl = sqlite3ExprCollSeq(pParse, p); + if( ExprUseXSelect(pExpr) ){ + Expr *pRhs = pExpr->x.pSelect->pEList->a[i].pExpr; + pColl = sqlite3BinaryCompareCollSeq(pParse, p, pRhs); + }else{ + /* If the RHS of the IN(...) expression are scalar expressions, do + ** not consider their collation sequences. The documentation says + ** "The collating sequence used for expressions of the form "x IN (y, z, + ** ...)" is the collating sequence of x.". */ + pColl = sqlite3ExprCollSeq(pParse, p); + } sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, (void*)pColl, P4_COLLSEQ); @@ -117305,26 +117387,37 @@ static int exprCodeInlineFunction( } /* -** Expression Node callback for sqlite3ExprCanReturnSubtype(). +** Expression Node callback for sqlite3ExprCanReturnSubtype(). If +** pExpr is able to return a subtype, set pWalker->eCode and abort +** the search. If pExpr can never return a subtype, prune search. ** -** Only a function call is able to return a subtype. So if the node -** is not a function call, return WRC_Prune immediately. +** The only expressions that can return a subtype are: ** -** A function call is able to return a subtype if it has the -** SQLITE_RESULT_SUBTYPE property. +** 1. A function +** 2. The no-op "+" operator +** 3. A CASE...END expression +** 4. A CAST() expression +** 5. A "expr COLLATE colseq" expression. ** -** Assume that every function is able to pass-through a subtype from -** one of its argument (using sqlite3_result_value()). Most functions -** are not this way, but we don't have a mechanism to distinguish those -** that are from those that are not, so assume they all work this way. -** That means that if one of its arguments is another function and that -** other function is able to return a subtype, then this function is -** able to return a subtype. +** For any other kind of expression, prune the search. +** +** For case 1, the expression can yield a subtype if the function has +** the SQLITE_RESULT_SUBTYPE property. Functions can also return +** a subtype (via sqlite3_result_value()) if any of the arguments can +** return a subtype. +** +** In all cases 1 through 5, the expression might also return a subtype +** if any operand can return a subtype. */ static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){ int n; FuncDef *pDef; sqlite3 *db; + if( pExpr->op==TK_CASE || pExpr->op==TK_UPLUS + || pExpr->op==TK_COLLATE || pExpr->op==TK_CAST + ){ + return WRC_Continue; + } if( pExpr->op!=TK_FUNCTION ){ return WRC_Prune; } @@ -117334,7 +117427,7 @@ static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){ pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0); if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){ pWalker->eCode = 1; - return WRC_Prune; + return WRC_Abort; } return WRC_Continue; } @@ -123123,7 +123216,9 @@ SQLITE_PRIVATE void sqlite3AlterDropConstraint( if( !pTab ) return; if( pCons ){ - zArg = sqlite3MPrintf(db, "%.*Q", pCons->n, pCons->z); + char *z = sqlite3NameFromToken(db, pCons); + zArg = sqlite3MPrintf(db, "%Q", z); + sqlite3DbFree(db, z); }else{ int iCol; if( alterFindCol(pParse, pTab, pCol, &iCol) ) return; @@ -123310,19 +123405,31 @@ SQLITE_PRIVATE void sqlite3AlterAddConstraint( SrcList *pSrc, /* Table to add constraint to */ Token *pFirst, /* First token of new constraint */ Token *pName, /* Name of new constraint. NULL if name omitted. */ - const char *pExpr, /* Text of CHECK expression */ - int nExpr /* Size of pExpr in bytes */ + const char *zExpr, /* Text of CHECK expression */ + int nExpr, /* Size of pExpr in bytes */ + Expr *pExpr /* The parsed CHECK expression */ ){ Table *pTab = 0; /* Table identified by pSrc */ int iDb = 0; /* Which schema does pTab live in */ const char *zDb = 0; /* Name of the schema in which pTab lives */ const char *pCons = 0; /* Text of the constraint */ int nCons; /* Bytes of text to use from pCons[] */ + int rc; /* Result from error checking pExpr */ /* Look up the table being altered. */ assert( pSrc->nSrc==1 ); pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, 1); - if( !pTab ) return; + if( !pTab ){ + sqlite3ExprDelete(pParse->db, pExpr); + return; + } + + /* Verify that the new CHECK constraint does not contain any + ** internal-use-only function. Forum post 2026-05-10T01:11:28Z + */ + rc = sqlite3ResolveSelfReference(pParse, pTab, NC_IsCheck, pExpr, 0); + sqlite3ExprDelete(pParse->db, pExpr); + if( rc ) return; /* If this new constraint has a name, check that it is not a duplicate of ** an existing constraint. It is an error if it is. */ @@ -123343,7 +123450,7 @@ SQLITE_PRIVATE void sqlite3AlterAddConstraint( sqlite3NestedParse(pParse, "SELECT sqlite_fail('constraint failed', %d) " "FROM %Q.%Q WHERE (%.*s) IS NOT TRUE", - SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, pExpr + SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr ); /* Edit the SQL for the named table. */ @@ -125505,6 +125612,16 @@ static void attachFunc( ** from sqlite3_deserialize() to close database db->init.iDb and ** reopen it as a MemDB */ Btree *pNewBt = 0; + + pNew = &db->aDb[db->init.iDb]; + assert( pNew->pBt!=0 ); + if( sqlite3BtreeTxnState(pNew->pBt)!=SQLITE_TXN_NONE + || sqlite3BtreeIsInBackup(pNew->pBt) + ){ + rc = SQLITE_BUSY; + goto attach_error; + } + pVfs = sqlite3_vfs_find("memdb"); if( pVfs==0 ) return; rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNewBt, 0, SQLITE_OPEN_MAIN_DB); @@ -125514,8 +125631,7 @@ static void attachFunc( /* Both the Btree and the new Schema were allocated successfully. ** Close the old db and update the aDb[] slot with the new memdb ** values. */ - pNew = &db->aDb[db->init.iDb]; - if( ALWAYS(pNew->pBt) ) sqlite3BtreeClose(pNew->pBt); + sqlite3BtreeClose(pNew->pBt); pNew->pBt = pNewBt; pNew->pSchema = pNewSchema; }else{ @@ -134011,9 +134127,18 @@ static void printfFunc( sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); str.printfFlags = SQLITE_PRINTF_SQLFUNC; sqlite3_str_appendf(&str, zFormat, &x); - n = str.nChar; - sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, - SQLITE_DYNAMIC); + if( str.accError==SQLITE_OK ){ + n = str.nChar; + sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, + SQLITE_DYNAMIC); + }else{ + if( str.accError==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_error_toobig(context); + } + sqlite3_str_reset(&str); + } } } @@ -135651,11 +135776,16 @@ static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ assert( p->cnt>0 ); p->cnt--; if( !p->approx ){ - if( sqlite3SubInt64(&p->iSum, sqlite3_value_int64(argv[0])) ){ - p->ovrfl = 1; - p->approx = 1; + i64 x = p->iSum; + if( sqlite3SubInt64(&x, sqlite3_value_int64(argv[0]))==0 ){ + p->iSum = x; + return; } - }else if( type==SQLITE_INTEGER ){ + p->ovrfl = 1; + p->approx = 1; + kahanBabuskaNeumaierInit(p, p->iSum); + } + if( type==SQLITE_INTEGER ){ i64 iVal = sqlite3_value_int64(argv[0]); if( iVal!=SMALLEST_INT64 ){ kahanBabuskaNeumaierStepInt64(p, -iVal); @@ -136628,47 +136758,46 @@ static void percentSort(double *a, unsigned int n){ int i; /* Loop counter */ double rPivot; /* The pivot value */ - assert( n>=2 ); - if( a[0]>a[n-1] ){ - SWAP_DOUBLE(a[0],a[n-1]) - } - if( n==2 ) return; - iGt = n-1; - i = n/2; - if( a[0]>a[i] ){ - SWAP_DOUBLE(a[0],a[i]) - }else if( a[i]>a[iGt] ){ - SWAP_DOUBLE(a[i],a[iGt]) - } - if( n==3 ) return; - rPivot = a[i]; - iLt = i = 1; - do{ - if( a[i]iLt ) SWAP_DOUBLE(a[i],a[iLt]) - iLt++; - i++; - }else if( a[i]>rPivot ){ - do{ - iGt--; - }while( iGt>i && a[iGt]>rPivot ); - SWAP_DOUBLE(a[i],a[iGt]) - }else{ - i++; + while( n>=2 ){ + if( a[0]>a[n-1] ){ + SWAP_DOUBLE(a[0],a[n-1]) + } + if( n==2 ) return; + iGt = n-1; + i = n/2; + if( a[0]>a[i] ){ + SWAP_DOUBLE(a[0],a[i]) + }else if( a[i]>a[iGt] ){ + SWAP_DOUBLE(a[i],a[iGt]) + } + if( n==3 ) return; + rPivot = a[i]; + iLt = i = 1; + do{ + if( a[i]iLt ) SWAP_DOUBLE(a[i],a[iLt]) + iLt++; + i++; + }else if( a[i]>rPivot ){ + do{ + iGt--; + }while( iGt>i && a[iGt]>rPivot ); + SWAP_DOUBLE(a[i],a[iGt]) + }else{ + i++; + } + }while( in/2 ){ + if( n-iGt>=2 ) percentSort(a+iGt, n-iGt); + n = iLt; + }else{ + if( iLt>=2 ) percentSort(a, iLt); + a += iGt; + n -= iGt; } - }while( i=2 ) percentSort(a, iLt); - if( n-iGt>=2 ) percentSort(a+iGt, n-iGt); - -/* Uncomment for testing */ -#if 0 - for(i=0; ipSrc!=0) && p->pSrc->nSrcpLimit==0 || p->pLimit->pRight==0) ){ if( pWhere->op==TK_AND ){ Expr *pRight = pWhere->pRight; @@ -156105,7 +156235,6 @@ static SQLITE_NOINLINE void existsToJoin( sqlite3TreeViewSelect(0, p, 0); } #endif - existsToJoin(pParse, p, pSubWhere); } } } @@ -156166,8 +156295,11 @@ static int selectCheckOnClausesExpr(Walker *pWalker, Expr *pExpr){ ** does not refer to a table to the right of CheckOnCtx.iJoin. */ do { SrcList *pSrc = pCtx->pSrc; + int nSrc = pSrc->nSrc; int iTab = pExpr->iTable; - if( iTab>=pSrc->a[0].iCursor && iTab<=pSrc->a[pSrc->nSrc-1].iCursor ){ + int ii; + for(ii=0; iia[ii].iCursor!=iTab; ii++){} + if( iiiJoin && iTab>pCtx->iJoin ){ sqlite3ErrorMsg(pWalker->pParse, "%s references tables to its right", @@ -165947,7 +166079,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). */ - if( pWInfo->nLevel>1 ){ + if( pWInfo->nLevel>1 || pTabItem->fg.fromExists ){ int nNotReady; /* The number of notReady tables */ SrcItem *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; @@ -165960,6 +166092,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( for(k=1; k<=nNotReady; k++){ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } + + /* Clear the fromExists flag on the OR-optimized table entry so that + ** the calls to sqlite3WhereEnd() do not code early-exits after the + ** first row is visited. The early exit applies to this table's + ** overall loop - including the multiple OR branches and any WHERE + ** conditions not passed to the sub-loops - not to the sub-loops. */ + pOrTab->a[0].fg.fromExists = 0; }else{ pOrTab = pWInfo->pTabList; } @@ -166203,7 +166342,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( assert( pLevel->op==OP_Return ); pLevel->p2 = sqlite3VdbeCurrentAddr(v); - if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); } + if( pWInfo->pTabList!=pOrTab ){ sqlite3DbFreeNN(db, pOrTab); } if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ @@ -166360,6 +166499,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; + if( ExprHasProperty(pAlt->pExpr, EP_Collate) ) continue; if( (pAlt->eOperator & WO_IN) && ExprUseXSelect(pAlt->pExpr) && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) @@ -167552,8 +167692,8 @@ static void exprAnalyzeOrTerm( ** 3. Not originating in the ON clause of an OUTER JOIN ** 4. The operator is not IS or else the query does not contain RIGHT JOIN ** 5. The affinities of A and B must be compatible -** 6a. Both operands use the same collating sequence OR -** 6b. The overall collating sequence is BINARY +** 6. Both operands use the same collating sequence, and they must not +** use explicit COLLATE clauses. ** If this routine returns TRUE, that means that the RHS can be substituted ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. ** This is an optimization. No harm comes from returning 0. But if 1 is @@ -167561,10 +167701,9 @@ static void exprAnalyzeOrTerm( */ static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){ char aff1, aff2; - CollSeq *pColl; if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */ if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */ - if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* (3) */ + if( ExprHasProperty(pExpr, EP_OuterON|EP_Collate) ) return 0; /* (3) */ assert( pSrc!=0 ); if( pExpr->op==TK_IS && pSrc->nSrc>=2 @@ -167579,10 +167718,7 @@ static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){ ){ return 0; /* (5) */ } - pColl = sqlite3ExprCompareCollSeq(pParse, pExpr); - if( !sqlite3IsBinary(pColl) - && !sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight) - ){ + if( !sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight) ){ return 0; /* (6) */ } return 1; @@ -167914,7 +168050,7 @@ static void exprAnalyze( /* Analyze a term that is composed of two or more subterms connected by ** an OR operator. */ - else if( pExpr->op==TK_OR ){ + else if( pExpr->op==TK_OR && !ExprHasProperty(pExpr, EP_Collate) ){ assert( pWC->op==TK_AND ); exprAnalyzeOrTerm(pSrc, pWC, idxTerm); pTerm = &pWC->a[idxTerm]; @@ -171732,7 +171868,8 @@ static int whereRangeVectorLen( idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); if( aff!=idxaff ) break; - pColl = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr); + if( ExprHasProperty(pTerm->pExpr, EP_Commuted) ) SWAP(Expr*, pRhs, pLhs); + pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); if( pColl==0 ) break; if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; } @@ -176128,27 +176265,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ } #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ } - if( pTabList->a[pLevel->iFrom].fg.fromExists - && (i==pWInfo->nLevel-1 - || pTabList->a[pWInfo->a[i+1].iFrom].fg.fromExists==0) - ){ - /* This is an EXISTS-to-JOIN optimization which is either the - ** inner-most loop, or the inner-most of a group of nested - ** EXISTS-to-JOIN optimization loops. If this loop sees a successful - ** row, it should break out of itself as well as other EXISTS-to-JOIN - ** loops in which is is directly nested. */ - int nOuter = 0; /* Nr of outer EXISTS that this one is nested within */ - while( nOutera[pLevel[-nOuter-1].iFrom].fg.fromExists ) break; - nOuter++; - } - testcase( nOuter>0 ); - sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel[-nOuter].addrBrk); - if( nOuter ){ - VdbeComment((v, "EXISTS break %d..%d", i-nOuter, i)); - }else{ - VdbeComment((v, "EXISTS break %d", i)); - } + if( pTabList->a[pLevel->iFrom].fg.fromExists ){ + /* This is an EXISTS-to-JOIN optimization loop. If this loop sees a + ** successful row, it should break out of itself. */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); + VdbeComment((v, "EXISTS break %d", i)); } sqlite3VdbeResolveLabel(v, pLevel->addrCont); if( pLevel->op!=OP_Noop ){ @@ -184222,9 +184343,11 @@ static YYACTIONTYPE yy_reduce( ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454); yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); if( yymsp[-4].minor.yy454 ){ + int i; yymsp[-4].minor.yy454->x.pList = pList; - if( ALWAYS(pList->nExpr) ){ - yymsp[-4].minor.yy454->flags |= pList->a[0].pExpr->flags & EP_Propagate; + for(i=0; inExpr; i++){ + assert( pList->a[i].pExpr!=0 ); + yymsp[-4].minor.yy454->flags |= pList->a[i].pExpr->flags & EP_Propagate; } }else{ sqlite3ExprListDelete(pParse->db, pList); @@ -184335,6 +184458,7 @@ static YYACTIONTYPE yy_reduce( yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy454, 0); if( yymsp[-4].minor.yy454 ){ yymsp[-4].minor.yy454->x.pList = pList; + sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy454); }else{ sqlite3ExprListDelete(pParse->db, pList); } @@ -184691,15 +184815,13 @@ static YYACTIONTYPE yy_reduce( break; case 300: /* cmd ::= ALTER TABLE fullname ADD CONSTRAINT nm CHECK LP expr RP onconf */ { - sqlite3AlterAddConstraint(pParse, yymsp[-8].minor.yy203, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1)); + sqlite3AlterAddConstraint(pParse, yymsp[-8].minor.yy203, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1), yymsp[-2].minor.yy454); } - yy_destructor(yypParser,219,&yymsp[-2].minor); break; case 301: /* cmd ::= ALTER TABLE fullname ADD CHECK LP expr RP onconf */ { - sqlite3AlterAddConstraint(pParse, yymsp[-6].minor.yy203, &yymsp[-4].minor.yy0, 0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1)); + sqlite3AlterAddConstraint(pParse, yymsp[-6].minor.yy203, &yymsp[-4].minor.yy0, 0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1), yymsp[-2].minor.yy454); } - yy_destructor(yypParser,219,&yymsp[-2].minor); break; case 302: /* cmd ::= create_vtab */ {sqlite3VtabFinishParse(pParse,0);} @@ -193903,6 +194025,12 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk); SQLITE_EXTENSION_INIT1 #endif + +/* +** Assume any b-tree layer with more levels than this is corrupt. +*/ +#define FTS3_MAX_BTREE_HEIGHT 48 + typedef struct Fts3HashWrapper Fts3HashWrapper; struct Fts3HashWrapper { Fts3Hash hash; /* Hash table */ @@ -195619,7 +195747,11 @@ static int fts3SelectLeaf( assert( piLeaf || piLeaf2 ); fts3GetVarint32(zNode, &iHeight); - rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + if( iHeight>FTS3_MAX_BTREE_HEIGHT ){ + rc = FTS_CORRUPT_VTAB; + }else{ + rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + } assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ @@ -200148,7 +200280,7 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ /* State 3. The integer just read is a column number. */ default: assert( eState==3 ); iCol = (int)v; - if( iCol<1 ){ + if( iCol<1 || iCol>(pFts3->nColumn+1) ){ rc = SQLITE_CORRUPT_VTAB; break; } @@ -200838,6 +200970,7 @@ static int getNextNode( assert( nKey==4 ); if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear); + if( nNear>=1000000000 ) nNear = 1000000000; } } @@ -210701,7 +210834,7 @@ static int fts3ExprLHits( if( p->flag==FTS3_MATCHINFO_LHITS ){ p->aMatchinfo[iStart + iCol] = (u32)nHit; }else if( nHit ){ - p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F)); + p->aMatchinfo[iStart + iCol/32] |= (1U << (iCol&0x1F)); } } assert( *pIter==0x00 || *pIter==0x01 ); @@ -213191,7 +213324,7 @@ static void jsonAppendSqlValue( break; } case SQLITE_FLOAT: { - jsonPrintf(100, p, "%!0.15g", sqlite3_value_double(pValue)); + jsonPrintf(100, p, "%!0.17g", sqlite3_value_double(pValue)); break; } case SQLITE_INTEGER: { @@ -214505,9 +214638,10 @@ static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){ u8 x; u32 sz; u32 n; - assert( i<=pParse->nBlob ); - x = pParse->aBlob[i]>>4; - if( x<=11 ){ + if( i>=pParse->nBlob ){ + *pSz = 0; + return 0; + }else if( (x = pParse->aBlob[i]>>4)<=11 ){ sz = x; n = 1; }else if( x==12 ){ @@ -217290,11 +217424,9 @@ static void jsonGroupInverse( UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); -#ifdef NEVER /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will ** always have been called to initialize it */ if( NEVER(!pStr) ) return; -#endif z = pStr->zBuf; for(i=1; inUsed && ((c = z[i])!=',' || inStr || nNest); i++){ if( c=='"' ){ @@ -217323,6 +217455,13 @@ static void jsonGroupInverse( ** json_group_obj(NAME,VALUE) ** ** Return a JSON object composed of all names and values in the aggregate. +** +** Rows for which NAME is NULL do not result in a new entry. However, we +** do initially insert a "@" entry into the growing string for each null entry +** and change the first character of the string to "@" to signal that the +** string contains null entries. The "@" markers are needed in order to +** correctly process xInverse() requests. The initial "@" is converted +** back into "{" and the "@" null values are removed by jsonObjectCompute(). */ static void jsonObjectStep( sqlite3_context *ctx, @@ -217340,7 +217479,7 @@ static void jsonObjectStep( if( pStr->zBuf==0 ){ jsonStringInit(pStr, ctx); jsonAppendChar(pStr, '{'); - }else if( pStr->nUsed>1 && z!=0 ){ + }else if( pStr->nUsed>1 ){ jsonAppendChar(pStr, ','); } pStr->pCtx = ctx; @@ -217348,6 +217487,9 @@ static void jsonObjectStep( jsonAppendString(pStr, z, n); jsonAppendChar(pStr, ':'); jsonAppendSqlValue(pStr, argv[1]); + }else{ + pStr->zBuf[0] = '@'; + jsonAppendRawNZ(pStr, "@", 1); } } } @@ -217356,20 +217498,64 @@ static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); if( pStr ){ - jsonAppendRawNZ(pStr, "}", 2); - jsonStringTrimOneChar(pStr); + JsonString *pOgStr = pStr; + JsonString tmpStr; + jsonAppendRawNZ(pOgStr, "}", 2); /* Ensure it is zero-terminated */ + jsonStringTrimOneChar(pOgStr); /* Remove the zero terminator */ pStr->pCtx = ctx; if( pStr->eErr ){ jsonReturnString(pStr, 0, 0); return; - }else if( flags & JSON_BLOB ){ + } + if( pStr->zBuf[0]!='{' ){ + /* The string contains null entries that need to be removed */ + u64 i, j; + int inStr = 0; + if( !isFinal ){ + /* Work with a temporary copy of the string if this is not the + ** final result */ + jsonStringInit(&tmpStr, ctx); + jsonAppendRawNZ(&tmpStr, pStr->zBuf, pStr->nUsed+1); + pStr = &tmpStr; + if( pStr->eErr ){ + jsonReturnString(pStr, 0, 0); + return; + } + jsonStringTrimOneChar(pStr); /* Remove zero terminator */ + } + /* Fix up the string by changing the initial "@" flag back to + ** to "{" and removing all subsequence "@" entries, with their + ** associated comma delimeters. */ + pStr->zBuf[0] = '{'; + for(i=j=1; inUsed; i++){ + char c = pStr->zBuf[i]; + if( c=='"' ){ + inStr = !inStr; + pStr->zBuf[j++] = '"'; + }else if( c=='\\' ){ + pStr->zBuf[j++] = '\\'; + pStr->zBuf[j++] = pStr->zBuf[++i]; + }else if( c=='@' && !inStr ){ + assert( i+1nUsed ); + if( pStr->zBuf[i+1]==',' ){ + i++; + }else if( pStr->zBuf[j-1]==',' ){ + j--; + } + }else{ + pStr->zBuf[j++] = c; + } + } + pStr->zBuf[j] = 0; /* Restore zero terminator */ + pStr->nUsed = j; /* Truncate the string */ + } + if( flags & JSON_BLOB ){ jsonReturnStringAsBlob(pStr); if( isFinal ){ if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf); }else{ - jsonStringTrimOneChar(pStr); + jsonStringTrimOneChar(pOgStr); } - return; }else if( isFinal ){ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, pStr->bStatic ? SQLITE_TRANSIENT : @@ -217377,8 +217563,9 @@ static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ pStr->bStatic = 1; }else{ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); - jsonStringTrimOneChar(pStr); + jsonStringTrimOneChar(pOgStr); } + if( pStr!=pOgStr ) jsonStringReset(pStr); }else if( flags & JSON_BLOB ){ static const unsigned char emptyObject = 0x0c; sqlite3_result_blob(ctx, &emptyObject, 1, SQLITE_STATIC); @@ -218230,7 +218417,7 @@ struct Rtree { u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ u8 nBytesPerCell; /* Bytes consumed per cell */ u8 inWrTrans; /* True if inside write transaction */ - u8 nAux; /* # of auxiliary columns in %_rowid */ + u16 nAux; /* # of auxiliary columns in %_rowid */ #ifdef SQLITE_ENABLE_GEOPOLY u8 nAuxNotNull; /* Number of initial not-null aux columns */ #endif @@ -219466,7 +219653,7 @@ static int nodeRowidIndex( ){ int ii; int nCell = NCELL(pNode); - assert( nCell<200 ); + assert( nCell<65536 && nCell>=0 ); for(ii=0; iiRTREE_MAXCELLS ){ + RTREE_IS_CORRUPT(pRtree); + return SQLITE_CORRUPT_VTAB; + } pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); while( p->iCellRTREE_MAX_AUX_COLUMN+3 ){ *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]); return SQLITE_ERROR; @@ -223624,6 +223814,11 @@ static int geopolyInit( int ii; (void)pAux; + if( argc>=RTREE_MAX_AUX_COLUMN+4 ){ + *pzErr = sqlite3_mprintf("Too many columns for a geopoly table"); + return SQLITE_ERROR; + } + sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); @@ -224758,7 +224953,7 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ const UChar *zInput; /* Pointer to input string */ UChar *zOutput = 0; /* Pointer to output buffer */ int nInput; /* Size of utf-16 input string in bytes */ - int nOut; /* Size of output buffer in bytes */ + sqlite3_int64 nOut; /* Size of output buffer in bytes */ int cnt; int bToUpper; /* True for toupper(), false for tolower() */ UErrorCode status; @@ -224781,7 +224976,7 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ } for(cnt=0; cnt<2; cnt++){ - UChar *zNew = sqlite3_realloc(zOutput, nOut); + UChar *zNew = sqlite3_realloc64(zOutput, nOut); if( zNew==0 ){ sqlite3_free(zOutput); sqlite3_result_error_nomem(p); @@ -224790,9 +224985,9 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ zOutput = zNew; status = U_ZERO_ERROR; if( bToUpper ){ - nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); + nOut = 2LL*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); }else{ - nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); + nOut = 2LL*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); } if( U_SUCCESS(status) ){ @@ -232507,12 +232702,13 @@ static int dbpageFilter( pCsr->szPage = sqlite3BtreeGetPageSize(pBt); pCsr->mxPgno = sqlite3BtreeLastPage(pBt); if( idxNum & 1 ){ + i64 iPg = sqlite3_value_int64(argv[idxNum>>1]); assert( argc>(idxNum>>1) ); - pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]); - if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){ + if( iPg<1 || iPg>pCsr->mxPgno ){ pCsr->pgno = 1; pCsr->mxPgno = 0; }else{ + pCsr->pgno = (Pgno)iPg; pCsr->mxPgno = pCsr->pgno; } }else{ @@ -233952,10 +234148,11 @@ static int sessionSerialLen(const u8 *a){ int n; assert( a!=0 ); e = *a; - if( e==0 || e==0xFF ) return 1; - if( e==SQLITE_NULL ) return 1; if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; - return sessionVarintGet(&a[1], &n) + 1 + n; + if( e==SQLITE_TEXT || e==SQLITE_BLOB ){ + return sessionVarintGet(&a[1], &n) + 1 + n; + } + return 1; } /* @@ -233978,17 +234175,17 @@ static unsigned int sessionChangeHash( u8 *a = aRecord; /* Used to iterate through change record */ for(i=0; inCol; i++){ - int eType = *a; int isPK = pTab->abPK[i]; if( bPkOnly && isPK==0 ) continue; - assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT - || eType==SQLITE_TEXT || eType==SQLITE_BLOB - || eType==SQLITE_NULL || eType==0 - ); - if( isPK ){ - a++; + int eType = *a++; + + assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT + || eType==SQLITE_TEXT || eType==SQLITE_BLOB + || eType==SQLITE_NULL || eType==0 + ); + h = sessionHashAppendType(h, eType); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ h = sessionHashAppendI64(h, sessionGetI64(a)); @@ -234858,6 +235055,16 @@ static int sessionPrepareDfltStmt( return rc; } +/* +** Finalize statement pStmt. If (*pRc) is SQLITE_OK when this function is +** called, set it to the results of the sqlite3_finalize() call. Or, if +** it is already set to an error code, leave it as is. +*/ +static void sessionFinalizeStmt(sqlite3_stmt *pStmt, int *pRc){ + int rc = sqlite3_finalize(pStmt); + if( *pRc==SQLITE_OK ) *pRc = rc; +} + /* ** Table pTab has one or more existing change-records with old.* records ** with fewer than pTab->nCol columns. This function updates all such @@ -234880,9 +235087,8 @@ static int sessionUpdateChanges(sqlite3_session *pSession, SessionTable *pTab){ } } + sessionFinalizeStmt(pStmt, &rc); pSession->rc = rc; - rc = sqlite3_finalize(pStmt); - if( pSession->rc==SQLITE_OK ) pSession->rc = rc; return pSession->rc; } @@ -235450,7 +235656,7 @@ static int sessionDiffFindNew( rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; @@ -235513,7 +235719,7 @@ static int sessionDiffFindModified( rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; @@ -236208,11 +236414,11 @@ static int sessionSelectStmt( ); sessionAppendStr(&cols, "tbl, ?2, stat", &rc); }else{ - #if 0 +#if 0 if( bRowid ){ sessionAppendStr(&cols, SESSIONS_ROWID, &rc); } - #endif +#endif for(i=0; iiNext+nByte)>pIn->nData ){ + if( rc==SQLITE_OK && (pIn->iNext+nByte)>pIn->nData ){ rc = SQLITE_CORRUPT_BKPT; } } @@ -237464,7 +237672,13 @@ static int sessionChangesetInvert( /* Test for EOF. */ if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert; - if( pInput->iNext>=pInput->nData ) break; + if( pInput->iNext+1>=pInput->nData ){ + if( pInput->iNext!=pInput->nData ){ + rc = SQLITE_CORRUPT_BKPT; + goto finished_invert; + } + break; + } eType = pInput->aData[pInput->iNext]; switch( eType ){ @@ -237660,6 +237874,7 @@ struct SessionApplyCtx { u8 bRebaseStarted; /* If table header is already in rebase */ u8 bRebase; /* True to collect rebase information */ u8 bIgnoreNoop; /* True to ignore no-op conflicts */ + u8 bNoUpdateLoop; /* No update-loop processing */ int bRowid; char *zErr; /* Error message, if any */ }; @@ -238233,7 +238448,7 @@ static int sessionConflictHandler( u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; int nBlob = pIter->in.iNext - pIter->in.iCurrent; sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); - return SQLITE_OK; + return rc; }else if( p->bIgnoreNoop==0 || op!=SQLITE_DELETE || eType==SQLITE_CHANGESET_CONFLICT ){ @@ -238355,7 +238570,7 @@ static int sessionApplyOneOp( for(i=0; rc==SQLITE_OK && iabPK[i] || (bPatchset==0 && pOld) ){ + if( pOld && (p->abPK[i] || bPatchset==0) ){ rc = sessionBindValue(pUp, i*2+2, pOld); } if( rc==SQLITE_OK && pNew ){ @@ -238481,7 +238696,264 @@ static int sessionApplyOneWithRetry( } /* -** Retry the changes accumulated in the pApply->constraints buffer. +** Create an iterator to iterate through the retry buffer pRetry. +*/ +static int sessionRetryIterInit( + SessionBuffer *pRetry, /* Buffer to iterate through */ + int bPatchset, /* True for patchset, false for changeset */ + const char *zTab, /* Table name */ + SessionApplyCtx *pApply, /* Session apply context */ + sqlite3_changeset_iter **ppIter /* OUT: New iterator */ +){ + sqlite3_changeset_iter *pRet = 0; + int rc = SQLITE_OK; + + rc = sessionChangesetStart( + &pRet, 0, 0, pRetry->nBuf, pRetry->aBuf, pApply->bInvertConstraints, 1 + ); + if( rc==SQLITE_OK ){ + size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); + pRet->bPatchset = bPatchset; + pRet->zTab = (char*)zTab; + pRet->nCol = pApply->nCol; + pRet->abPK = pApply->abPK; + sessionBufferGrow(&pRet->tblhdr, nByte, &rc); + pRet->apValue = (sqlite3_value**)pRet->tblhdr.aBuf; + if( rc==SQLITE_OK ){ + memset(pRet->apValue, 0, nByte); + }else{ + sqlite3changeset_finalize(pRet); + pRet = 0; + } + } + + *ppIter = pRet; + return rc; +} + +/* +** Attempt to apply all the changes in retry buffer pRetry to the database. +** Except, if parameter iSkip is greater than or equal to 0, skip change +** iSkip. +*/ +static int sessionApplyRetryBuffer( + SessionBuffer *pRetry, /* Buffer to apply changes from */ + int iSkip, /* If >=0, index of change to omit */ + sqlite3 *db, /* Database handle */ + int bPatchset, /* True for patchset, false for changeset */ + const char *zTab, /* Name of table to write to */ + SessionApplyCtx *pApply, /* Apply context */ + int(*xConflict)(void*, int, sqlite3_changeset_iter*), + void *pCtx /* First argument passed to xConflict */ +){ + int rc = SQLITE_OK; + int rc2 = SQLITE_OK; + int ii = 0; + sqlite3_changeset_iter *pIter = 0; + + assert( pApply->constraints.nBuf==0 ); + + rc = sessionRetryIterInit(pRetry, bPatchset, zTab, pApply, &pIter); + + for(ii=0; rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter); ii++){ + if( ii!=iSkip ){ + rc = sessionApplyOneWithRetry(db, pIter, pApply, xConflict, pCtx); + } + } + + rc2 = sqlite3changeset_finalize(pIter); + if( rc==SQLITE_OK ) rc = rc2; + assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); + + return rc; +} + +/* +** Check if table zTab in the "main" database of db is a WITHOUT ROWID +** table. +** +** If no error occurs, return SQLITE_OK and set output variable (*pbWR) to +** true if zTab is a WITHOUT ROWID table, or false otherwise. Or, if an +** error does occur, return an SQLite error code. The final value of (*pbWR) +** is undefined in this case. +*/ +static int sessionTableIsWithoutRowid(sqlite3 *db, const char *zTab, int *pbWR){ + sqlite3_stmt *pList = 0; + char *zSql = 0; + int rc = SQLITE_OK; + + zSql = sqlite3_mprintf("PRAGMA table_list = %Q", zTab); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(db, zSql, -1, &pList, 0); + sqlite3_free(zSql); + } + + if( rc==SQLITE_OK ){ + sqlite3_step(pList); + *pbWR = sqlite3_column_int(pList, 4); + rc = sqlite3_finalize(pList); + } + + return rc; +} + +/* +** Iterator pUp points to an UPDATE change. This function deletes the +** affected row from the database and creates an INSERT statement that +** may be used to reinsert the row as it is after the UPDATE change +** has been applied. +** +** If successful, SQLITE_OK is returned and output variable (*ppInsert) +** is left pointing to a prepared INSERT statement. It is the responsibility +** of the caller to eventually free this statement using sqlite3_finalize(). +** Or, if an error occurs, an SQLite error code is returned and (*ppInsert) +** set to NULL. pApply->zErr may be set to an error message in this case. +*/ +static int sessionUpdateToDeleteInsert( + sqlite3 *db, /* Database to write to */ + const char *zTab, /* Table name */ + SessionApplyCtx *pApply, /* Apply context */ + sqlite3_changeset_iter *pUp, /* Iterator pointing to UPDATE change */ + sqlite3_stmt **ppInsert /* OUT: INSERT statement */ +){ + sqlite3_stmt *pRet = 0; /* The INSERT statement */ + sqlite3_stmt *pSelect = 0; /* SELECT to read current values of row */ + int rc = SQLITE_OK; + int bWR = 0; + + rc = sessionTableIsWithoutRowid(db, zTab, &bWR); + if( rc==SQLITE_OK ){ + char *zSelect = 0; + char *zInsert = 0; + SessionBuffer cols = {0, 0, 0}; + SessionBuffer insbind = {0, 0, 0}; + SessionBuffer pkcols = {0, 0, 0}; + SessionBuffer selbind = {0, 0, 0}; + + const char *zComma = ""; + const char *zComma2 = ""; + int ii; + for(ii=0; iinCol; ii++){ + sessionAppendStr(&cols, zComma, &rc); + sessionAppendIdent(&cols, pApply->azCol[ii], &rc); + sessionAppendStr(&insbind, zComma, &rc); + sessionAppendStr(&insbind, "?", &rc); + zComma = ", "; + + if( pApply->abPK[ii] ){ + sessionAppendStr(&pkcols, zComma2, &rc); + sessionAppendIdent(&pkcols, pApply->azCol[ii], &rc); + sessionAppendStr(&selbind, zComma2, &rc); + sessionAppendPrintf(&selbind, &rc, "?%d", ii+1); + zComma2 = ", "; + } + } + if( bWR==0 ){ + sessionAppendStr(&cols, zComma, &rc); + sessionAppendStr(&cols, SESSIONS_ROWID, &rc); + sessionAppendStr(&insbind, zComma, &rc); + sessionAppendStr(&insbind, "?", &rc); + } + + if( rc==SQLITE_OK ){ + zSelect = sqlite3_mprintf("SELECT %s FROM %Q WHERE (%s) IS (%s)", + cols.aBuf, zTab, pkcols.aBuf, selbind.aBuf + ); + if( zSelect==0 ) rc = SQLITE_NOMEM; + } + if( rc==SQLITE_OK ){ + zInsert = sqlite3_mprintf("INSERT INTO %Q(%s) VALUES(%s)", + zTab, cols.aBuf, insbind.aBuf + ); + if( zInsert==0 ) rc = SQLITE_NOMEM; + } + + if( rc==SQLITE_OK ){ + rc = sessionPrepare(db, &pSelect, &pApply->zErr, zSelect); + } + if( rc==SQLITE_OK ){ + rc = sessionPrepare(db, &pRet, &pApply->zErr, zInsert); + } + + sqlite3_free(zSelect); + sqlite3_free(zInsert); + sqlite3_free(cols.aBuf); + sqlite3_free(insbind.aBuf); + sqlite3_free(pkcols.aBuf); + sqlite3_free(selbind.aBuf); + } + + if( rc==SQLITE_OK ){ + rc = sessionBindRow( + pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pSelect + ); + } + + if( rc==SQLITE_OK && sqlite3_step(pSelect)==SQLITE_ROW ){ + int iCol; + for(iCol=0; iColnCol; iCol++){ + sqlite3_value *pVal = pUp->apValue[iCol+pApply->nCol]; + if( pVal==0 ){ + pVal = sqlite3_column_value(pSelect, iCol); + } + rc = sqlite3_bind_value(pRet, iCol+1, pVal); + } + if( bWR==0 ){ + sqlite3_bind_int64(pRet, iCol+1, sqlite3_column_int64(pSelect, iCol)); + } + } + sessionFinalizeStmt(pSelect, &rc); + + /* Delete the row from the database. */ + if( rc==SQLITE_OK ){ + rc = sessionBindRow( + pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pApply->pDelete + ); + sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); + } + if( rc==SQLITE_OK ){ + sqlite3_step(pApply->pDelete); + rc = sqlite3_reset(pApply->pDelete); + } + + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pRet); + pRet = 0; + } + + *ppInsert = pRet; + return rc; +} + +/* +** Retry the changes accumulated in the pApply->constraints buffer. The +** pApply->constraints buffer contains all changes to table zTab that +** could not be applied due to SQLITE_CONSTRAINT errors. This function +** attempts to apply them as follows: +** +** 1) It runs through the buffer and attempts to retry each change, +** removing any that are successfully applied from the buffer. This +** is repeated until no further progress can be made. +** +** 2) For each UPDATE change in the buffer, try the following in a +** savepoint transaction: +** +** a) DELETE the affected row, +** b) Attempt step (1) with remaining changes, +** c) Attempt to INSERT a row equivalent to the one that would be +** created by applying this UPDATE change. +** +** If the INSERT in (c) succeeds, the savepoint is committed and all +** successfully applied changes are removed from the buffer. Step (2) +** is then repeated. +** +** 3) Once step (2) has been attempted for each UPDATE in the change, +** a final attempt is made to apply each remaining change. This time, +** if an SQLITE_CONSTRAINT error is encountered, the conflict handler +** is invoked and the user has to decide whether to omit the change +** or rollback the entire _apply() operation. */ static int sessionRetryConstraints( sqlite3 *db, @@ -238492,41 +238964,101 @@ static int sessionRetryConstraints( void *pCtx /* First argument passed to xConflict */ ){ int rc = SQLITE_OK; + int iUpdate = 0; + /* Step (1) */ while( pApply->constraints.nBuf ){ - sqlite3_changeset_iter *pIter2 = 0; SessionBuffer cons = pApply->constraints; memset(&pApply->constraints, 0, sizeof(SessionBuffer)); - rc = sessionChangesetStart( - &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints, 1 + rc = sessionApplyRetryBuffer( + &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx ); - if( rc==SQLITE_OK ){ - size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); - int rc2; - pIter2->bPatchset = bPatchset; - pIter2->zTab = (char*)zTab; - pIter2->nCol = pApply->nCol; - pIter2->abPK = pApply->abPK; - sessionBufferGrow(&pIter2->tblhdr, nByte, &rc); - pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf; - if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte); - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){ - rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx); - } - - rc2 = sqlite3changeset_finalize(pIter2); - if( rc==SQLITE_OK ) rc = rc2; - } - assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); sqlite3_free(cons.aBuf); if( rc!=SQLITE_OK ) break; - if( pApply->constraints.nBuf>=cons.nBuf ){ - /* No progress was made on the last round. */ - pApply->bDeferConstraints = 0; + + /* If no progress has been made this round, break out of the loop. */ + if( pApply->constraints.nBuf>=cons.nBuf ) break; + } + + /* Step (2) */ + while( rc==SQLITE_OK && pApply->constraints.nBuf && !pApply->bNoUpdateLoop ){ + SessionBuffer cons = {0, 0, 0}; + sqlite3_changeset_iter *pUp = 0; + sqlite3_stmt *pInsert = 0; + int iSkip = 0; + + rc = sessionRetryIterInit( + &pApply->constraints, bPatchset, zTab, pApply, &pUp + ); + if( rc==SQLITE_OK ){ + int iThis = -1; + while( SQLITE_ROW==sqlite3changeset_next(pUp) ){ + if( pUp->op==SQLITE_UPDATE ) iThis++; + if( iThis==iUpdate ) break; + iSkip++; + } + if( iThis==iUpdate ){ + rc = sqlite3_exec(db, "SAVEPOINT update_op", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = sessionUpdateToDeleteInsert(db, zTab, pApply, pUp, &pInsert); + } + } + sqlite3changeset_finalize(pUp); + if( iThis!=iUpdate ) break; } + + if( rc==SQLITE_OK ){ + cons = pApply->constraints; + + while( rc==SQLITE_OK && pApply->constraints.nBuf>0 ){ + SessionBuffer app = pApply->constraints; + memset(&pApply->constraints, 0, sizeof(SessionBuffer)); + rc = sessionApplyRetryBuffer( + &app, iSkip, db, bPatchset, zTab, pApply, xConflict, pCtx + ); + if( app.aBuf!=cons.aBuf ){ + sqlite3_free(app.aBuf); + } + if( pApply->constraints.nBuf>=app.nBuf ){ + break; + } + iSkip = -1; + } + } + + iUpdate++; + if( rc==SQLITE_OK ){ + sqlite3_step(pInsert); + rc = sqlite3_finalize(pInsert); + if( rc==SQLITE_CONSTRAINT ){ + rc = sqlite3_exec(db, "ROLLBACK TO update_op", 0, 0, 0); + sqlite3_free(pApply->constraints.aBuf); + pApply->constraints = cons; + memset(&cons, 0, sizeof(cons)); + }else if( rc==SQLITE_OK ){ + iUpdate = 0; + } + if( rc==SQLITE_OK ){ + rc = sqlite3_exec(db, "RELEASE update_op", 0, 0, 0); + } + }else{ + sqlite3_finalize(pInsert); + } + + sqlite3_free(cons.aBuf); + } + + /* Step (3) */ + if( rc==SQLITE_OK && pApply->constraints.nBuf ){ + SessionBuffer cons = pApply->constraints; + memset(&pApply->constraints, 0, sizeof(SessionBuffer)); + pApply->bDeferConstraints = 0; + rc = sessionApplyRetryBuffer( + &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx + ); + sqlite3_free(cons.aBuf); } return rc; @@ -238580,6 +239112,7 @@ static int sessionChangesetApply( sApply.bRebase = (ppRebase && pnRebase); sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); sApply.bIgnoreNoop = !!(flags & SQLITE_CHANGESETAPPLY_IGNORENOOP); + sApply.bNoUpdateLoop = !!(flags & SQLITE_CHANGESETAPPLY_NOUPDATELOOP); if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); } @@ -240391,7 +240924,7 @@ SQLITE_API int sqlite3changegroup_change_blob( const void *pVal, int nVal ){ - sqlite3_int64 nByte = 1 + sessionVarintLen(nVal) + nVal; + sqlite3_int64 nByte = 1 + sessionVarintLen(nVal) + (i64)nVal; int rc = SQLITE_OK; SessionBuffer *pBuf = 0; @@ -250975,7 +251508,7 @@ static void fts5DataRelease(Fts5Data *pData){ static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){ Fts5Data *pRet = fts5DataRead(p, iRowid); if( pRet ){ - if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){ + if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){ FTS5_CORRUPT_ROWID(p, iRowid); fts5DataRelease(pRet); pRet = 0; @@ -252629,6 +253162,10 @@ static void fts5LeafSeek( if( nKeepn ){ + FTS5_CORRUPT_ITER(p, pIter); + return; + } assert( nKeep>=nMatch ); if( nKeep==nMatch ){ @@ -253605,8 +254142,7 @@ static void fts5PoslistFilterCallback( do { while( ieState ){ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart); @@ -253755,7 +254291,7 @@ static void fts5IndexExtractColset( /* Advance pointer p until it points to pEnd or an 0x01 byte that is ** not part of a varint */ while( paiCol[i]==iCurrent ){ @@ -253852,8 +254388,11 @@ static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS ); assert( pIter->pColset ); + assert( pIter->poslist.nSpace>=pIter->pIndex->pConfig->nCol ); - if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){ + if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf + || pSeg->nPos>pIter->pIndex->pConfig->nCol + ){ fts5IterSetOutputs_Col(pIter, pSeg); }else{ u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset]; @@ -255347,6 +255886,11 @@ static void fts5DoSecureDelete( }else{ iStart = fts5GetU16(&aPg[0]); } + if( iStart>nPg ){ + FTS5_CORRUPT_IDX(p); + sqlite3_free(aIdx); + return; + } iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta); assert_nc( iSOP<=pSeg->iLeafOffset ); @@ -263223,7 +263767,7 @@ static void fts5SourceIdFunc( ){ assert( nArg==0 ); UNUSED_PARAM2(nArg, apUnused); - sqlite3_result_text(pCtx, "fts5: 2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b", -1, SQLITE_TRANSIENT); + sqlite3_result_text(pCtx, "fts5: 2026-06-03 19:12:13 d6e03d8c777cfa2d35e3b60d8ec3e0187f3e9f99d8e2ee9cac695fd6fcdf1a24", -1, SQLITE_TRANSIENT); } /* @@ -265617,8 +266161,14 @@ static int fts5PorterCreate( const char *zBase = "unicode61"; fts5_tokenizer_v2 *pV2 = 0; - if( nArg>0 ){ - zBase = azArg[0]; + while( nArg>0 ){ + if( sqlite3_stricmp(azArg[0],"porter")==0 ){ + nArg--; + azArg++; + }else{ + zBase = azArg[0]; + break; + } } pRet = (PorterTokenizer*)sqlite3_malloc64(sizeof(PorterTokenizer)); diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h index 7ae4e90d368..7ea576038ae 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3-binding.h @@ -147,12 +147,12 @@ extern "C" { ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.53.0" -#define SQLITE_VERSION_NUMBER 3053000 -#define SQLITE_SOURCE_ID "2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b" -#define SQLITE_SCM_BRANCH "trunk" -#define SQLITE_SCM_TAGS "release major-release version-3.53.0" -#define SQLITE_SCM_DATETIME "2026-04-09T11:41:38.498Z" +#define SQLITE_VERSION "3.53.2" +#define SQLITE_VERSION_NUMBER 3053002 +#define SQLITE_SOURCE_ID "2026-06-03 19:12:13 d6e03d8c777cfa2d35e3b60d8ec3e0187f3e9f99d8e2ee9cac695fd6fcdf1a24" +#define SQLITE_SCM_BRANCH "branch-3.53" +#define SQLITE_SCM_TAGS "release version-3.53.2" +#define SQLITE_SCM_DATETIME "2026-06-03T19:12:13.350Z" /* ** CAPI3REF: Run-Time Library Version Numbers @@ -12854,11 +12854,23 @@ SQLITE_API int sqlite3changeset_apply_v3( ** database behave as if they were declared with "ON UPDATE NO ACTION ON ** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL ** or SET DEFAULT. +** +**

SQLITE_CHANGESETAPPLY_NOUPDATELOOP
+** Sometimes, a changeset contains two or more update statements such that +** although after applying all updates the database will contain no +** constraint violations, no single update can be applied before the others. +** The simplest example of this is a pair of UPDATEs that have "swapped" +** two column values with a UNIQUE constraint. +**

+** Usually, sqlite3changeset_apply() and similar functions work hard to try +** to find a way to apply such a changeset. However, if this flag is set, +** then all such updates are considered CONSTRAINT conflicts. */ #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 #define SQLITE_CHANGESETAPPLY_INVERT 0x0002 #define SQLITE_CHANGESETAPPLY_IGNORENOOP 0x0004 #define SQLITE_CHANGESETAPPLY_FKNOACTION 0x0008 +#define SQLITE_CHANGESETAPPLY_NOUPDATELOOP 0x0010 /* ** CAPI3REF: Constants Passed To The Conflict Handler diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3.go b/vendor/github.com/mattn/go-sqlite3/sqlite3.go index b9deb72aa58..656d2dc677f 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3.go @@ -69,13 +69,13 @@ _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zV } static int -_sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) { - return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT); +_sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, sqlite3_uint64 np) { + return sqlite3_bind_text64(stmt, n, p, np, SQLITE_TRANSIENT, SQLITE_UTF8); } static int -_sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) { - return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT); +_sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, sqlite3_uint64 np) { + return sqlite3_bind_blob64(stmt, n, p, np, SQLITE_TRANSIENT); } typedef struct { @@ -220,8 +220,8 @@ _sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_ } #endif -void _sqlite3_result_text(sqlite3_context* ctx, const char* s) { - sqlite3_result_text(ctx, s, -1, &free); +void _sqlite3_result_text(sqlite3_context* ctx, const char* s, int n) { + sqlite3_result_text(ctx, s, n, &free); } void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) { @@ -476,6 +476,12 @@ type SQLiteStmt struct { cls bool // True if the statement was created by SQLiteConn.Query namedParams map[string][3]int cacheKey string + metadata *sqliteStmtMetadata +} + +type sqliteStmtMetadata struct { + cols []string + decltype []string } // SQLiteResult implements sql.Result. @@ -2069,7 +2075,9 @@ func (c *SQLiteConn) GetFilename(schemaName string) string { if schemaName == "" { schemaName = "main" } - return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName))) + cSchema := C.CString(schemaName) + defer C.free(unsafe.Pointer(cSchema)) + return C.GoString(C.sqlite3_db_filename(c.db, cSchema)) } // GetLimit returns the current value of a run-time limit. @@ -2180,9 +2188,9 @@ var placeHolder = []byte{0} func bindText(s *C.sqlite3_stmt, n C.int, v string) C.int { if len(v) == 0 { - return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0)) + return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.sqlite3_uint64(0)) } - return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(unsafe.StringData(v))), C.int(len(v))) + return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(unsafe.StringData(v))), C.sqlite3_uint64(len(v))) } func bindValue(s *C.sqlite3_stmt, n C.int, value driver.Value) C.int { @@ -2208,14 +2216,14 @@ func bindValue(s *C.sqlite3_stmt, n C.int, value driver.Value) C.int { if ln == 0 { v = placeHolder } - return C._sqlite3_bind_blob(s, n, unsafe.Pointer(&v[0]), C.int(ln)) + return C._sqlite3_bind_blob(s, n, unsafe.Pointer(&v[0]), C.sqlite3_uint64(ln)) case time.Time: var buf [64]byte b := v.AppendFormat(buf[:0], SQLiteTimestampFormats[0]) if len(b) == 0 { - return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0)) + return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.sqlite3_uint64(0)) } - return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b))) + return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&b[0])), C.sqlite3_uint64(len(b))) default: return C.SQLITE_MISUSE } @@ -2475,6 +2483,36 @@ func (rc *SQLiteRows) Close() error { return nil } +func (s *SQLiteStmt) cacheMetadata() bool { + return !s.cls || s.cacheKey != "" +} + +func (s *SQLiteStmt) columnNamesLocked(n int) []string { + if s.metadata == nil { + s.metadata = &sqliteStmtMetadata{} + } + if len(s.metadata.cols) != n { + s.metadata.cols = make([]string, n) + for i := range s.metadata.cols { + s.metadata.cols[i] = C.GoString(C.sqlite3_column_name(s.s, C.int(i))) + } + } + return s.metadata.cols +} + +func (s *SQLiteStmt) declTypesLocked(n int) []string { + if s.metadata == nil { + s.metadata = &sqliteStmtMetadata{} + } + if len(s.metadata.decltype) != n { + s.metadata.decltype = make([]string, n) + for i := range s.metadata.decltype { + s.metadata.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(s.s, C.int(i)))) + } + } + return s.metadata.decltype +} + // Columns return column names. func (rc *SQLiteRows) Columns() []string { if rc.s == nil { @@ -2483,9 +2521,13 @@ func (rc *SQLiteRows) Columns() []string { rc.s.mu.Lock() defer rc.s.mu.Unlock() if rc.s.s != nil && int(rc.nc) != len(rc.cols) { - rc.cols = make([]string, rc.nc) - for i := range rc.cols { - rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) + if rc.s.cacheMetadata() { + rc.cols = rc.s.columnNamesLocked(int(rc.nc)) + } else { + rc.cols = make([]string, rc.nc) + for i := range rc.cols { + rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i))) + } } } return rc.cols @@ -2493,9 +2535,13 @@ func (rc *SQLiteRows) Columns() []string { func (rc *SQLiteRows) declTypes() []string { if rc.s.s != nil && rc.decltype == nil { - rc.decltype = make([]string, rc.nc) - for i := range rc.decltype { - rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))) + if rc.s.cacheMetadata() { + rc.decltype = rc.s.declTypesLocked(int(rc.nc)) + } else { + rc.decltype = make([]string, rc.nc) + for i := range rc.decltype { + rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))) + } } } return rc.decltype diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go index 7c7431dcce1..4436279e9c7 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_context.go @@ -28,7 +28,6 @@ import "C" import ( "math" - "reflect" "unsafe" ) @@ -91,9 +90,15 @@ func (c *SQLiteContext) ResultNull() { // ResultText sets the result of an SQL function. // See: sqlite3_result_text, http://sqlite.org/c3ref/result_blob.html func (c *SQLiteContext) ResultText(s string) { - h := (*reflect.StringHeader)(unsafe.Pointer(&s)) - cs, l := (*C.char)(unsafe.Pointer(h.Data)), C.int(h.Len) - C.my_result_text((*C.sqlite3_context)(c), cs, l) + if i64 && len(s) > math.MaxInt32 { + C.sqlite3_result_error_toobig((*C.sqlite3_context)(c)) + return + } + if len(s) == 0 { + C.my_result_text((*C.sqlite3_context)(c), (*C.char)(unsafe.Pointer(&placeHolder[0])), 0) + return + } + C.my_result_text((*C.sqlite3_context)(c), (*C.char)(unsafe.Pointer(unsafe.StringData(s))), C.int(len(s))) } // ResultZeroblob sets the result of an SQL function. diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_dbstat.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_dbstat.go new file mode 100644 index 00000000000..d0338461441 --- /dev/null +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_dbstat.go @@ -0,0 +1,15 @@ +// Copyright (C) 2025 Yasuhiro Matsumoto . +// Copyright (C) 2025 Jakob Borg . +// +// Use of this source code is governed by an MIT-style +// license that can be found in the LICENSE file. + +//go:build sqlite_dbstat +// +build sqlite_dbstat + +package sqlite3 + +/* +#cgo CFLAGS: -DSQLITE_ENABLE_DBSTAT_VTAB +*/ +import "C" diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go index 3ac8050a4a2..dddb655da81 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_unlock_notify.go @@ -21,6 +21,7 @@ package sqlite3 extern void unlock_notify_callback(void *arg, int argc); */ import "C" + import ( "fmt" "math" @@ -82,7 +83,7 @@ func unlock_notify_wait(db *C.sqlite3) C.int { h := unt.add(c) defer unt.remove(h) - pargv := C.malloc(C.sizeof_uint) + pargv := C.malloc(C.size_t(unsafe.Sizeof(uint(0)))) defer C.free(pargv) argv := (*[1]uint)(pargv) diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go index 9761bf3570e..7c2ae58e5d5 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3_opt_vtable.go @@ -270,7 +270,6 @@ import "C" import ( "fmt" "math" - "reflect" "unsafe" ) @@ -329,11 +328,7 @@ type InfoOrderBy struct { } func constraints(info *C.sqlite3_index_info) []InfoConstraint { - slice := *(*[]C.struct_sqlite3_index_constraint)(unsafe.Pointer(&reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(info.aConstraint)), - Len: int(info.nConstraint), - Cap: int(info.nConstraint), - })) + slice := unsafe.Slice(info.aConstraint, int(info.nConstraint)) cst := make([]InfoConstraint, 0, len(slice)) for _, c := range slice { @@ -351,11 +346,7 @@ func constraints(info *C.sqlite3_index_info) []InfoConstraint { } func orderBys(info *C.sqlite3_index_info) []InfoOrderBy { - slice := *(*[]C.struct_sqlite3_index_orderby)(unsafe.Pointer(&reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(info.aOrderBy)), - Len: int(info.nOrderBy), - Cap: int(info.nOrderBy), - })) + slice := unsafe.Slice(info.aOrderBy, int(info.nOrderBy)) ob := make([]InfoOrderBy, 0, len(slice)) for _, c := range slice { @@ -400,10 +391,7 @@ func goMInit(db, pClientData unsafe.Pointer, argc C.int, argv **C.char, pzErr ** return 0 } args := make([]string, argc) - var A []*C.char - slice := reflect.SliceHeader{Data: uintptr(unsafe.Pointer(argv)), Len: int(argc), Cap: int(argc)} - a := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&slice)).Elem().Interface() - for i, s := range a.([]*C.char) { + for i, s := range unsafe.Slice(argv, int(argc)) { args[i] = C.GoString(s) } var vTab VTab @@ -466,11 +454,7 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char { // Get a pointer to constraint_usage struct so we can update in place. - slice := *(*[]C.struct_sqlite3_index_constraint_usage)(unsafe.Pointer(&reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(info.aConstraintUsage)), - Len: int(info.nConstraint), - Cap: int(info.nConstraint), - })) + slice := unsafe.Slice(info.aConstraintUsage, int(info.nConstraint)) index := 1 for i := range slice { if res.Used[i] { @@ -488,11 +472,7 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char { } info.needToFreeIdxStr = C.int(1) - idxStr := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(info.idxStr)), - Len: len(res.IdxStr) + 1, - Cap: len(res.IdxStr) + 1, - })) + idxStr := unsafe.Slice((*byte)(unsafe.Pointer(info.idxStr)), len(res.IdxStr)+1) copy(idxStr, res.IdxStr) idxStr[len(idxStr)-1] = 0 // null-terminated string diff --git a/vendor/github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/spaces.go b/vendor/github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/spaces.go index ced3254ba90..42bc5dfe674 100644 --- a/vendor/github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/spaces.go +++ b/vendor/github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/spaces.go @@ -1269,8 +1269,7 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool, } // space managers are allowed to disable and delete their project spaces - rp, err := p.AssemblePermissions(ctx, n) - if err == nil && permissions.IsManager(rp) { + if rp, err := p.AssemblePermissions(ctx, n); err == nil && permissions.IsManager(rp) { return nil } @@ -1284,10 +1283,5 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool, return nil } - // active space, user has no grant at all: hide existence rather than reveal it - if err == nil && !rp.GetStat() && !n.IsDisabled(ctx) { - return errtypes.NotFound(spaceID) - } - return errtypes.PermissionDenied(fmt.Sprintf("user is not allowed to delete space %s", n.ID)) } diff --git a/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/models.go b/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/models.go index 48701fcb403..d712d68d9c2 100644 --- a/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/models.go +++ b/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/models.go @@ -1,5 +1,7 @@ package inotifywaitgo +import "log/slog" + type Settings struct { // Directory to watch Dir string @@ -13,6 +15,8 @@ type Settings struct { KillOthers bool // verbose Verbose bool + // Logger + Log *slog.Logger } type Options struct { diff --git a/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/watcher.go b/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/watcher.go index c77c30d1747..57db22d203d 100644 --- a/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/watcher.go +++ b/vendor/github.com/pablodz/inotifywaitgo/inotifywaitgo/watcher.go @@ -3,8 +3,9 @@ package inotifywaitgo import ( "bufio" "encoding/csv" + "errors" "fmt" - "log" + "log/slog" "os" "os/exec" "strings" @@ -14,13 +15,13 @@ import ( func WatchPath(s *Settings) { // Check if inotifywait is installed if ok, err := checkDependencies(); !ok || err != nil { - s.ErrorChan <- fmt.Errorf(NOT_INSTALLED) + s.ErrorChan <- errors.New(NOT_INSTALLED) return } // Check if the directory exists if _, err := os.Stat(s.Dir); os.IsNotExist(err) { - s.ErrorChan <- fmt.Errorf(DIR_NOT_EXISTS) + s.ErrorChan <- errors.New(DIR_NOT_EXISTS) return } @@ -49,15 +50,19 @@ func WatchPath(s *Settings) { return } + logger := s.Log + if logger == nil { + logger = slog.New(slog.NewTextHandler(os.Stdout, nil)) + } + // Read the output of inotifywait and split it into lines scanner := bufio.NewScanner(stdout) for scanner.Scan() { line := scanner.Text() - log.Println(line) parts, err := parseLine(line) if err != nil || len(parts) < 2 { - s.ErrorChan <- fmt.Errorf(INVALID_OUTPUT) + s.ErrorChan <- errors.New(INVALID_OUTPUT) continue } @@ -66,7 +71,7 @@ func WatchPath(s *Settings) { if s.Verbose { for _, eventStr := range eventStrs { - log.Printf("eventStr: <%s>, <%s>", eventStr, line) + logger.Debug("eventStr: <%s>, <%s>", eventStr, line) } } diff --git a/vendor/github.com/pierrec/lz4/v4/README.md b/vendor/github.com/pierrec/lz4/v4/README.md index 4629c9d0e03..dee77545b0c 100644 --- a/vendor/github.com/pierrec/lz4/v4/README.md +++ b/vendor/github.com/pierrec/lz4/v4/README.md @@ -21,7 +21,7 @@ go get github.com/pierrec/lz4/v4 There is a command line interface tool to compress and decompress LZ4 files. ``` -go install github.com/pierrec/lz4/v4/cmd/lz4c +go install github.com/pierrec/lz4/v4/cmd/lz4c@latest ``` Usage diff --git a/vendor/github.com/pierrec/lz4/v4/compressing_reader.go b/vendor/github.com/pierrec/lz4/v4/compressing_reader.go new file mode 100644 index 00000000000..8df0dc76d00 --- /dev/null +++ b/vendor/github.com/pierrec/lz4/v4/compressing_reader.go @@ -0,0 +1,222 @@ +package lz4 + +import ( + "errors" + "io" + + "github.com/pierrec/lz4/v4/internal/lz4block" + "github.com/pierrec/lz4/v4/internal/lz4errors" + "github.com/pierrec/lz4/v4/internal/lz4stream" +) + +type crState int + +const ( + crStateInitial crState = iota + crStateReading + crStateFlushing + crStateDone +) + +type CompressingReader struct { + state crState + src io.ReadCloser // source reader + level lz4block.CompressionLevel // how hard to try + frame *lz4stream.Frame // frame being built + in []byte + out ovWriter + handler func(int) +} + +// NewCompressingReader creates a reader which reads compressed data from +// raw stream. This makes it a logical opposite of a normal lz4.Reader. +// We require an io.ReadCloser as an underlying source for compatibility +// with Go's http.Request. +func NewCompressingReader(src io.ReadCloser) *CompressingReader { + zrd := &CompressingReader { + frame: lz4stream.NewFrame(), + } + + _ = zrd.Apply(DefaultBlockSizeOption, DefaultChecksumOption, defaultOnBlockDone) + zrd.Reset(src) + + return zrd +} + +// Source exposes the underlying source stream for introspection and control. +func (zrd *CompressingReader) Source() io.ReadCloser { + return zrd.src +} + +// Close simply invokes the underlying stream Close method. This method is +// provided for the benefit of Go http client/server, which relies on Close +// for goroutine termination. +func (zrd *CompressingReader) Close() error { + return zrd.src.Close() +} + +// Apply applies useful options to the lz4 encoder. +func (zrd *CompressingReader) Apply(options ...Option) (err error) { + if zrd.state != crStateInitial { + return lz4errors.ErrOptionClosedOrError + } + + zrd.Reset(zrd.src) + + for _, o := range options { + if err = o(zrd); err != nil { + return + } + } + return +} + +func (*CompressingReader) private() {} + +func (zrd *CompressingReader) init() error { + zrd.frame.InitW(&zrd.out, 1, false) + size := zrd.frame.Descriptor.Flags.BlockSizeIndex() + zrd.in = size.Get() + return zrd.frame.Descriptor.Write(zrd.frame, &zrd.out) +} + +// Read allows reading of lz4 compressed data +func (zrd *CompressingReader) Read(p []byte) (n int, err error) { + defer func() { + if err != nil { + zrd.state = crStateDone + } + }() + + if !zrd.out.reset(p) { + return len(p), nil + } + + switch zrd.state { + case crStateInitial: + err = zrd.init() + if err != nil { + return + } + zrd.state = crStateReading + case crStateDone: + return 0, errors.New("This reader is done") + case crStateFlushing: + if zrd.out.dataPos > 0 { + n = zrd.out.dataPos + zrd.out.data = nil + zrd.out.dataPos = 0 + return + } else { + zrd.state = crStateDone + return 0, io.EOF + } + } + + for zrd.state == crStateReading { + block := zrd.frame.Blocks.Block + + var rCount int + rCount, err = io.ReadFull(zrd.src, zrd.in) + switch err { + case nil: + err = block.Compress( + zrd.frame, zrd.in[ : rCount], zrd.level, + ).Write(zrd.frame, &zrd.out) + zrd.handler(len(block.Data)) + if err != nil { + return + } + + if zrd.out.dataPos == len(zrd.out.data) { + n = zrd.out.dataPos + zrd.out.dataPos = 0 + zrd.out.data = nil + return + } + case io.EOF, io.ErrUnexpectedEOF: // read may be partial + if rCount > 0 { + err = block.Compress( + zrd.frame, zrd.in[ : rCount], zrd.level, + ).Write(zrd.frame, &zrd.out) + zrd.handler(len(block.Data)) + if err != nil { + return + } + } + + err = zrd.frame.CloseW(&zrd.out, 1) + if err != nil { + return + } + zrd.state = crStateFlushing + + n = zrd.out.dataPos + zrd.out.dataPos = 0 + zrd.out.data = nil + return + default: + return + } + } + + err = lz4errors.ErrInternalUnhandledState + return +} + +// Reset makes the stream usable again; mostly handy to reuse lz4 encoder +// instances. +func (zrd *CompressingReader) Reset(src io.ReadCloser) { + zrd.frame.Reset(1) + zrd.state = crStateInitial + zrd.src = src + zrd.out.clear() +} + +type ovWriter struct { + data []byte + ov []byte + dataPos int + ovPos int +} + +func (wr *ovWriter) Write(p []byte) (n int, err error) { + count := copy(wr.data[wr.dataPos : ], p) + wr.dataPos += count + + if count < len(p) { + wr.ov = append(wr.ov, p[count : ]...) + } + + return len(p), nil +} + +func (wr *ovWriter) reset(out []byte) bool { + ovRem := len(wr.ov) - wr.ovPos + + if ovRem >= len(out) { + wr.ovPos += copy(out, wr.ov[wr.ovPos : ]) + return false + } + + if ovRem > 0 { + copy(out, wr.ov[wr.ovPos : ]) + wr.ov = wr.ov[ : 0] + wr.ovPos = 0 + wr.dataPos = ovRem + } else if wr.ovPos > 0 { + wr.ov = wr.ov[ : 0] + wr.ovPos = 0 + wr.dataPos = 0 + } + + wr.data = out + return true +} + +func (wr *ovWriter) clear() { + wr.data = nil + wr.dataPos = 0 + wr.ov = wr.ov[ : 0] + wr.ovPos = 0 +} diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/block.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/block.go index 9054998fe72..fec8adb03a1 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/block.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/block.go @@ -31,11 +31,10 @@ func recoverBlock(e *error) { } } -// blockHash hashes the lower five bytes of x into a value < htSize. +// blockHash hashes the lower 6 bytes into a value < htSize. func blockHash(x uint64) uint32 { const prime6bytes = 227718039650203 - x &= 1<<40 - 1 - return uint32((x * prime6bytes) >> (64 - hashLog)) + return uint32(((x << (64 - 48)) * prime6bytes) >> (64 - hashLog)) } func CompressBlockBound(n int) int { @@ -123,9 +122,9 @@ func (c *Compressor) CompressBlock(src, dst []byte) (int, error) { goto lastLiterals } - // Fast scan strategy: the hash table only stores the last five-byte sequences. + // Fast scan strategy: the hash table only stores the last 4 bytes sequences. for si < sn { - // Hash the next five bytes (sequence)... + // Hash the next 6 bytes (sequence)... match := binary.LittleEndian.Uint64(src[si:]) h := blockHash(match) h2 := blockHash(match >> 8) diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/blocks.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/blocks.go index a1bfa99e4b4..0956f34f246 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/blocks.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/blocks.go @@ -1,25 +1,25 @@ // Package lz4block provides LZ4 BlockSize types and pools of buffers. package lz4block -import "sync" +import ( + "fmt" + "sync" +) const ( Block64Kb uint32 = 1 << (16 + iota*2) Block256Kb Block1Mb Block4Mb + Block8Mb = 2 * Block4Mb ) -// In legacy mode all blocks are compressed regardless -// of the compressed size: use the bound size. -var Block8Mb = uint32(CompressBlockBound(8 << 20)) - var ( - BlockPool64K = sync.Pool{New: func() interface{} { return make([]byte, Block64Kb) }} - BlockPool256K = sync.Pool{New: func() interface{} { return make([]byte, Block256Kb) }} - BlockPool1M = sync.Pool{New: func() interface{} { return make([]byte, Block1Mb) }} - BlockPool4M = sync.Pool{New: func() interface{} { return make([]byte, Block4Mb) }} - BlockPool8M = sync.Pool{New: func() interface{} { return make([]byte, Block8Mb) }} + blockPool64K = sync.Pool{New: func() interface{} { return &[Block64Kb]byte{} }} + blockPool256K = sync.Pool{New: func() interface{} { return &[Block256Kb]byte{} }} + blockPool1M = sync.Pool{New: func() interface{} { return &[Block1Mb]byte{} }} + blockPool4M = sync.Pool{New: func() interface{} { return &[Block4Mb]byte{} }} + blockPool8M = sync.Pool{New: func() interface{} { return &[Block8Mb]byte{} }} ) func Index(b uint32) BlockSizeIndex { @@ -53,35 +53,39 @@ func (b BlockSizeIndex) IsValid() bool { } func (b BlockSizeIndex) Get() []byte { - var buf interface{} switch b { case 4: - buf = BlockPool64K.Get() + return blockPool64K.Get().(*[Block64Kb]byte)[:] case 5: - buf = BlockPool256K.Get() + return blockPool256K.Get().(*[Block256Kb]byte)[:] case 6: - buf = BlockPool1M.Get() + return blockPool1M.Get().(*[Block1Mb]byte)[:] case 7: - buf = BlockPool4M.Get() + return blockPool4M.Get().(*[Block4Mb]byte)[:] case 3: - buf = BlockPool8M.Get() + return blockPool8M.Get().(*[Block8Mb]byte)[:] + default: + panic(fmt.Errorf("invalid block index %d", b)) } - return buf.([]byte) } func Put(buf []byte) { // Safeguard: do not allow invalid buffers. switch c := cap(buf); uint32(c) { case Block64Kb: - BlockPool64K.Put(buf[:c]) + blockPool64K.Put((*[Block64Kb]byte)(buf[:c])) case Block256Kb: - BlockPool256K.Put(buf[:c]) + blockPool256K.Put((*[Block256Kb]byte)(buf[:c])) case Block1Mb: - BlockPool1M.Put(buf[:c]) + blockPool1M.Put((*[Block1Mb]byte)(buf[:c])) case Block4Mb: - BlockPool4M.Put(buf[:c]) + blockPool4M.Put((*[Block4Mb]byte)(buf[:c])) case Block8Mb: - BlockPool8M.Put(buf[:c]) + blockPool8M.Put((*[Block8Mb]byte)(buf[:c])) + case 0: + // Allow "returning" an empty buffer. + default: + panic(fmt.Errorf("invalid block size %d", c)) } } diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_arm64.s b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_arm64.s index c43e8a8d28e..d2fe11b8ea1 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_arm64.s +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_arm64.s @@ -185,7 +185,7 @@ copyMatchTry8: // A 16-at-a-time loop doesn't provide a further speedup. CMP $8, len CCMP HS, offset, $8, $0 - BLO copyMatchLoop1 + BLO copyMatchTry4 AND $7, len, lenRem SUB $8, len @@ -201,8 +201,19 @@ copyMatchLoop8: MOVD tmp2, -8(dst) B copyMatchDone +copyMatchTry4: + // Copy words if both len and offset are at least four. + CMP $4, len + CCMP HS, offset, $4, $0 + BLO copyMatchLoop1 + + MOVWU.P 4(match), tmp2 + MOVWU.P tmp2, 4(dst) + SUBS $4, len + BEQ copyMatchDone + copyMatchLoop1: - // Byte-at-a-time copy for small offsets. + // Byte-at-a-time copy for small offsets <= 3. MOVBU.P 1(match), tmp2 MOVB.P tmp2, 1(dst) SUBS $1, len diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_other.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_other.go index 2010cd7468c..e1d36058522 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_other.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4block/decode_other.go @@ -32,30 +32,7 @@ func decodeBlock(dst, src, dict []byte) (ret int) { // Literals. if lLen := b >> 4; lLen > 0 { - switch { - case lLen < 0xF && si+16 < uint(len(src)): - // Shortcut 1 - // if we have enough room in src and dst, and the literals length - // is small enough (0..14) then copy all 16 bytes, even if not all - // are part of the literals. - copy(dst[di:], src[si:si+16]) - si += lLen - di += lLen - if mLen := b & 0xF; mLen < 0xF { - // Shortcut 2 - // if the match length (4..18) fits within the literals, then copy - // all 18 bytes, even if not all are part of the literals. - mLen += 4 - if offset := u16(src[si:]); mLen <= offset && offset < di { - i := di - offset - end := i + 18 - copy(dst[di:], dst[i:end]) - si += 2 - di += mLen - continue - } - } - case lLen == 0xF: + if lLen == 0xF { for { x := uint(src[si]) if lLen += x; int(lLen) < 0 { @@ -66,20 +43,27 @@ func decodeBlock(dst, src, dict []byte) (ret int) { break } } - fallthrough - default: - copy(dst[di:di+lLen], src[si:si+lLen]) - si += lLen - di += lLen } + if lLen <= 16 && si+16 < uint(len(src)) { + // Shortcut 1: if we have enough room in src and dst, and the + // literal length is at most 16, then copy 16 bytes, even if not + // all are part of the literal. The compiler inlines this copy. + copy(dst[di:di+16], src[si:si+16]) + } else { + copy(dst[di:di+lLen], src[si:si+lLen]) + } + si += lLen + di += lLen } + // Match. mLen := b & 0xF if si == uint(len(src)) && mLen == 0 { break } else if si >= uint(len(src)) { return hasError } + mLen += minMatch offset := u16(src[si:]) if offset == 0 { @@ -87,9 +71,17 @@ func decodeBlock(dst, src, dict []byte) (ret int) { } si += 2 - // Match. - mLen += minMatch - if mLen == minMatch+0xF { + if mLen <= 16 { + // Shortcut 2: if the match length is at most 16 and we're far + // enough from the end of dst, copy 16 bytes unconditionally + // so that the compiler can inline the copy. + if mLen <= offset && offset < di && di+16 <= uint(len(dst)) { + i := di - offset + copy(dst[di:di+16], dst[i:i+16]) + di += mLen + continue + } + } else if mLen >= 15+minMatch { for { x := uint(src[si]) if mLen += x; int(mLen) < 0 { diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4errors/errors.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4errors/errors.go index 710ea42812e..be116515217 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4errors/errors.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4errors/errors.go @@ -16,4 +16,5 @@ const ( ErrOptionInvalidBlockSize Error = "lz4: invalid block size" ErrOptionNotApplicable Error = "lz4: option not applicable" ErrWriterNotClosed Error = "lz4: writer not closed" + ErrEndOfStream Error = "lz4: end of stream reached" ) diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/block.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/block.go index 459086f09b2..52531dfeae1 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/block.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/block.go @@ -143,7 +143,7 @@ func (b *Blocks) initR(f *Frame, num int, src io.Reader) (chan []byte, error) { c <- nil // signal the collection loop that we are done <-c // wait for the collect loop to complete if f.isLegacy() && cum == cumx { - err = io.EOF + err = lz4errors.ErrEndOfStream } b.closeR(err) close(data) @@ -224,9 +224,7 @@ func (b *FrameDataBlock) Close(f *Frame) { func (b *FrameDataBlock) Compress(f *Frame, src []byte, level lz4block.CompressionLevel) *FrameDataBlock { data := b.data if f.isLegacy() { - // In legacy mode, the buffer is sized according to CompressBlockBound, - // but only 8Mb is buffered for compression. - src = src[:8<<20] + data = data[:cap(data)] } else { data = data[:len(src)] // trigger the incompressible flag in CompressBlock } @@ -248,7 +246,7 @@ func (b *FrameDataBlock) Compress(f *Frame, src []byte, level lz4block.Compressi b.src = src // keep track of the source for content checksum if f.Descriptor.Flags.BlockChecksum() { - b.Checksum = xxh32.ChecksumZero(src) + b.Checksum = xxh32.ChecksumZero(b.Data) } return b } @@ -292,11 +290,11 @@ func (b *FrameDataBlock) Read(f *Frame, src io.Reader, cum uint32) (uint32, erro // Only works in non concurrent mode, for concurrent mode // it is handled separately. // Linux kernel format appends the total uncompressed size at the end. - return 0, io.EOF + return 0, lz4errors.ErrEndOfStream } } else if x == 0 { // Marker for end of stream. - return 0, io.EOF + return 0, lz4errors.ErrEndOfStream } b.Size = DataBlockSize(x) @@ -330,7 +328,7 @@ func (b *FrameDataBlock) Uncompress(f *Frame, dst, dict []byte, sum bool) ([]byt dst = dst[:n] } if f.Descriptor.Flags.BlockChecksum() { - if c := xxh32.ChecksumZero(dst); c != b.Checksum { + if c := xxh32.ChecksumZero(b.data); c != b.Checksum { err := fmt.Errorf("%w: got %x; expected %x", lz4errors.ErrInvalidBlockChecksum, c, b.Checksum) return nil, err } diff --git a/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/frame.go b/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/frame.go index 18192a9433d..93c1f44b1b7 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/frame.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/lz4stream/frame.go @@ -5,7 +5,6 @@ import ( "encoding/binary" "fmt" "io" - "io/ioutil" "github.com/pierrec/lz4/v4/internal/lz4block" "github.com/pierrec/lz4/v4/internal/lz4errors" @@ -96,7 +95,7 @@ newFrame: if err != nil { return err } - if _, err := io.CopyN(ioutil.Discard, src, int64(skip)); err != nil { + if _, err := io.CopyN(io.Discard, src, int64(skip)); err != nil { return err } goto newFrame diff --git a/vendor/github.com/pierrec/lz4/v4/internal/xxh32/xxh32zero.go b/vendor/github.com/pierrec/lz4/v4/internal/xxh32/xxh32zero.go index 8d3206a87c5..651d10c1047 100644 --- a/vendor/github.com/pierrec/lz4/v4/internal/xxh32/xxh32zero.go +++ b/vendor/github.com/pierrec/lz4/v4/internal/xxh32/xxh32zero.go @@ -1,5 +1,5 @@ // Package xxh32 implements the very fast XXH hashing algorithm (32 bits version). -// (https://github.com/Cyan4973/XXH/) +// (ported from the reference implementation https://github.com/Cyan4973/xxHash/) package xxh32 import ( diff --git a/vendor/github.com/pierrec/lz4/v4/options.go b/vendor/github.com/pierrec/lz4/v4/options.go index 46a87380313..57a44e767dc 100644 --- a/vendor/github.com/pierrec/lz4/v4/options.go +++ b/vendor/github.com/pierrec/lz4/v4/options.go @@ -57,6 +57,13 @@ func BlockSizeOption(size BlockSize) Option { } w.frame.Descriptor.Flags.BlockSizeIndexSet(lz4block.Index(size)) return nil + case *CompressingReader: + size := uint32(size) + if !lz4block.IsValid(size) { + return fmt.Errorf("%w: %d", lz4errors.ErrOptionInvalidBlockSize, size) + } + w.frame.Descriptor.Flags.BlockSizeIndexSet(lz4block.Index(size)) + return nil } return lz4errors.ErrOptionNotApplicable } @@ -72,6 +79,9 @@ func BlockChecksumOption(flag bool) Option { case *Writer: w.frame.Descriptor.Flags.BlockChecksumSet(flag) return nil + case *CompressingReader: + w.frame.Descriptor.Flags.BlockChecksumSet(flag) + return nil } return lz4errors.ErrOptionNotApplicable } @@ -87,6 +97,9 @@ func ChecksumOption(flag bool) Option { case *Writer: w.frame.Descriptor.Flags.ContentChecksumSet(flag) return nil + case *CompressingReader: + w.frame.Descriptor.Flags.ContentChecksumSet(flag) + return nil } return lz4errors.ErrOptionNotApplicable } @@ -104,6 +117,10 @@ func SizeOption(size uint64) Option { w.frame.Descriptor.Flags.SizeSet(size > 0) w.frame.Descriptor.ContentSize = size return nil + case *CompressingReader: + w.frame.Descriptor.Flags.SizeSet(size > 0) + w.frame.Descriptor.ContentSize = size + return nil } return lz4errors.ErrOptionNotApplicable } @@ -162,6 +179,14 @@ func CompressionLevelOption(level CompressionLevel) Option { } w.level = lz4block.CompressionLevel(level) return nil + case *CompressingReader: + switch level { + case Fast, Level1, Level2, Level3, Level4, Level5, Level6, Level7, Level8, Level9: + default: + return fmt.Errorf("%w: %d", lz4errors.ErrOptionInvalidCompressionLevel, level) + } + w.level = lz4block.CompressionLevel(level) + return nil } return lz4errors.ErrOptionNotApplicable } @@ -186,6 +211,9 @@ func OnBlockDoneOption(handler func(size int)) Option { case *Reader: rw.handler = handler return nil + case *CompressingReader: + rw.handler = handler + return nil } return lz4errors.ErrOptionNotApplicable } diff --git a/vendor/github.com/pierrec/lz4/v4/reader.go b/vendor/github.com/pierrec/lz4/v4/reader.go index 275daad7cb9..094f4304790 100644 --- a/vendor/github.com/pierrec/lz4/v4/reader.go +++ b/vendor/github.com/pierrec/lz4/v4/reader.go @@ -63,7 +63,7 @@ func (r *Reader) Apply(options ...Option) (err error) { return } -// Size returns the size of the underlying uncompressed data, if set in the stream. +// Size returns the size of the current frame's uncompressed data, if set in the stream. func (r *Reader) Size() int { switch r.state.state { case readState, closedState: @@ -117,6 +117,7 @@ func (r *Reader) Read(buf []byte) (n int, err error) { for len(buf) > 0 { var bn int if r.idx == 0 { + read: if r.isNotConcurrent() { bn, err = r.read(buf) } else { @@ -129,12 +130,29 @@ func (r *Reader) Read(buf []byte) (n int, err error) { } switch err { case nil: + case lz4errors.ErrEndOfStream: + + // Read Checksum. + err = r.frame.CloseR(r.src) + if err != nil { + return + } + + //Check for new stream. + r.Reset(r.src) + if err = r.init(); r.state.next(err) { + return + } + + goto read case io.EOF: if er := r.frame.CloseR(r.src); er != nil { err = er } lz4block.Put(r.data) r.data = nil + // reset frame to release the buffer held by Block + r.frame.Reset(r.num) return default: return @@ -157,9 +175,9 @@ func (r *Reader) Read(buf []byte) (n int, err error) { } // read uncompresses the next block as follow: -// - if buf has enough room, the block is uncompressed into it directly -// and the lenght of used space is returned -// - else, the uncompress data is stored in r.data and 0 is returned +// - if buf has enough room, the block is uncompressed into it directly +// and the lenght of used space is returned +// - else, the uncompress data is stored in r.data and 0 is returned func (r *Reader) read(buf []byte) (int, error) { block := r.frame.Blocks.Block _, err := block.Read(r.frame, r.src, r.cum) @@ -189,6 +207,7 @@ func (r *Reader) read(buf []byte) (int, error) { } r.cum += uint32(len(dst)) if direct { + r.data = r.data[:0] return len(dst), nil } r.data = dst @@ -199,10 +218,8 @@ func (r *Reader) read(buf []byte) (int, error) { // initial state from NewReader, but instead reading from reader. // No access to reader is performed. func (r *Reader) Reset(reader io.Reader) { - if r.data != nil { - lz4block.Put(r.data) - r.data = nil - } + lz4block.Put(r.data) + r.data = nil r.frame.Reset(r.num) r.state.reset() r.src = reader @@ -212,6 +229,7 @@ func (r *Reader) Reset(reader io.Reader) { // WriteTo efficiently uncompresses the data from the Reader underlying source to w. func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { switch r.state.state { + case readState: case closedState, errorState: return 0, r.state.err case newState: @@ -232,6 +250,7 @@ func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { for { var bn int var dst []byte + read: if r.isNotConcurrent() { bn, err = r.read(data) dst = data[:bn] @@ -246,6 +265,21 @@ func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { } switch err { case nil: + case lz4errors.ErrEndOfStream: + // Read Checksum. + err = r.frame.CloseR(r.src) + if err != nil { + return + } + // Check for a new stream. + r.Reset(r.src) + if err = r.init(); r.state.next(err) { + if err == io.EOF { + err = nil + } + return + } + goto read case io.EOF: err = r.frame.CloseR(r.src) return diff --git a/vendor/github.com/pierrec/lz4/v4/state.go b/vendor/github.com/pierrec/lz4/v4/state.go index d94f04d05eb..532316eeca3 100644 --- a/vendor/github.com/pierrec/lz4/v4/state.go +++ b/vendor/github.com/pierrec/lz4/v4/state.go @@ -38,11 +38,15 @@ func (s *_State) reset() { s.err = nil } -// next sets the state to the next one unless it is passed a non nil error. -// It returns whether or not it is in error. +// next sets the state to the next one unless it is passed a non-nil error. +// It returns whether it is in error. func (s *_State) next(err error) bool { if err != nil { - s.err = fmt.Errorf("%s: %w", s.state, err) + if errors.Is(err, io.EOF) { + s.err = io.EOF + } else { + s.err = fmt.Errorf("%s: %w", s.state, err) + } s.state = errorState return true } @@ -61,15 +65,17 @@ func (s *_State) check(errp *error) { return } if err := *errp; err != nil { - s.err = fmt.Errorf("%w[%s]", err, s.state) - if !errors.Is(err, io.EOF) { - s.state = errorState + if errors.Is(err, io.EOF) { + s.err = io.EOF + } else { + s.err = fmt.Errorf("%w[%s]", err, s.state) } + s.state = errorState } } func (s *_State) fail() error { - s.state = errorState s.err = fmt.Errorf("%w[%s]", lz4errors.ErrInternalUnhandledState, s.state) + s.state = errorState return s.err } diff --git a/vendor/github.com/pierrec/lz4/v4/writer.go b/vendor/github.com/pierrec/lz4/v4/writer.go index 77699f2b54a..5637acde473 100644 --- a/vendor/github.com/pierrec/lz4/v4/writer.go +++ b/vendor/github.com/pierrec/lz4/v4/writer.go @@ -150,6 +150,10 @@ func (w *Writer) Flush() (err error) { case writeState: case errorState: return w.state.err + case newState: + if err = w.init(); w.state.next(err) { + return + } default: return nil } @@ -172,10 +176,8 @@ func (w *Writer) Close() error { } err := w.frame.CloseW(w.src, w.num) // It is now safe to free the buffer. - if w.data != nil { - lz4block.Put(w.data) - w.data = nil - } + lz4block.Put(w.data) + w.data = nil return err } @@ -186,6 +188,8 @@ func (w *Writer) Close() error { // // w.Close must be called before Reset or pending data may be dropped. func (w *Writer) Reset(writer io.Writer) { + lz4block.Put(w.data) + w.data = nil w.frame.Reset(w.num) w.state.reset() w.src = writer @@ -223,11 +227,13 @@ func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) { return } n += int64(rn) - err = w.write(data[:rn], true) - if err != nil { - return + if rn > 0 { + err = w.write(data[:rn], true) + if err != nil { + return + } + w.handler(rn) } - w.handler(rn) if !done && !w.isNotConcurrent() { // The buffer will be returned automatically by go routines (safe=true) // so get a new one fo the next round. diff --git a/vendor/github.com/prometheus/alertmanager/alert/state.go b/vendor/github.com/prometheus/alertmanager/alert/state.go index b6cd363f471..02dd7881771 100644 --- a/vendor/github.com/prometheus/alertmanager/alert/state.go +++ b/vendor/github.com/prometheus/alertmanager/alert/state.go @@ -22,3 +22,26 @@ const ( AlertStateActive AlertState = "active" AlertStateSuppressed AlertState = "suppressed" ) + +// Compare returns -1 if s has lower priority than other, 0 if equal, +// and 1 if higher. Priority order: suppressed > active > unprocessed. +func (s AlertState) Compare(other AlertState) int { + p := func(st AlertState) int { + switch st { + case AlertStateSuppressed: + return 2 + case AlertStateActive: + return 1 + default: + return 0 + } + } + switch a, b := p(s), p(other); { + case a < b: + return -1 + case a > b: + return 1 + default: + return 0 + } +} diff --git a/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go b/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go index e613704566e..3b5e65680dc 100644 --- a/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go +++ b/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go @@ -23,38 +23,42 @@ import ( const ( FeatureAlertNamesInMetrics = "alert-names-in-metrics" FeatureReceiverNameInMetrics = "receiver-name-in-metrics" + FeatureGroupKeyInMetrics = "group-key-in-metrics" FeatureClassicMode = "classic-mode" FeatureUTF8StrictMode = "utf8-strict-mode" FeatureAutoGOMEMLIMIT = "auto-gomemlimit" - FeatureAutoGOMAXPROCS = "auto-gomaxprocs" + FeatureEventRecorder = "event-recorder" ) var AllowedFlags = []string{ FeatureAlertNamesInMetrics, FeatureReceiverNameInMetrics, + FeatureGroupKeyInMetrics, FeatureClassicMode, FeatureUTF8StrictMode, FeatureAutoGOMEMLIMIT, - FeatureAutoGOMAXPROCS, + FeatureEventRecorder, } type Flagger interface { EnableAlertNamesInMetrics() bool EnableReceiverNamesInMetrics() bool + EnableGroupKeyInMetrics() bool ClassicMode() bool UTF8StrictMode() bool EnableAutoGOMEMLIMIT() bool - EnableAutoGOMAXPROCS() bool + EnableEventRecorder() bool } type Flags struct { logger *slog.Logger enableAlertNamesInMetrics bool enableReceiverNamesInMetrics bool + enableGroupKeyInMetrics bool classicMode bool utf8StrictMode bool enableAutoGOMEMLIMIT bool - enableAutoGOMAXPROCS bool + enableEventRecorder bool } func (f *Flags) EnableAlertNamesInMetrics() bool { @@ -65,6 +69,10 @@ func (f *Flags) EnableReceiverNamesInMetrics() bool { return f.enableReceiverNamesInMetrics } +func (f *Flags) EnableGroupKeyInMetrics() bool { + return f.enableGroupKeyInMetrics +} + func (f *Flags) ClassicMode() bool { return f.classicMode } @@ -77,8 +85,8 @@ func (f *Flags) EnableAutoGOMEMLIMIT() bool { return f.enableAutoGOMEMLIMIT } -func (f *Flags) EnableAutoGOMAXPROCS() bool { - return f.enableAutoGOMAXPROCS +func (f *Flags) EnableEventRecorder() bool { + return f.enableEventRecorder } type flagOption func(flags *Flags) @@ -89,6 +97,12 @@ func enableReceiverNameInMetrics() flagOption { } } +func enableGroupKeyInMetrics() flagOption { + return func(configs *Flags) { + configs.enableGroupKeyInMetrics = true + } +} + func enableClassicMode() flagOption { return func(configs *Flags) { configs.classicMode = true @@ -107,9 +121,9 @@ func enableAutoGOMEMLIMIT() flagOption { } } -func enableAutoGOMAXPROCS() flagOption { +func enableEventRecorder() flagOption { return func(configs *Flags) { - configs.enableAutoGOMAXPROCS = true + configs.enableEventRecorder = true } } @@ -135,6 +149,9 @@ func NewFlags(logger *slog.Logger, features string) (Flagger, error) { case FeatureReceiverNameInMetrics: opts = append(opts, enableReceiverNameInMetrics()) logger.Warn("Experimental receiver name in metrics enabled") + case FeatureGroupKeyInMetrics: + opts = append(opts, enableGroupKeyInMetrics()) + logger.Warn("Experimental group key in metrics enabled") case FeatureClassicMode: opts = append(opts, enableClassicMode()) logger.Warn("Classic mode enabled") @@ -144,9 +161,9 @@ func NewFlags(logger *slog.Logger, features string) (Flagger, error) { case FeatureAutoGOMEMLIMIT: opts = append(opts, enableAutoGOMEMLIMIT()) logger.Warn("Automatically set GOMEMLIMIT to match the Linux container or system memory limit.") - case FeatureAutoGOMAXPROCS: - opts = append(opts, enableAutoGOMAXPROCS()) - logger.Error("Deprecated: auto-gomaxprocs will be removed in v0.33. Removing this flag does not affect behavior, as Go 1.25+ natively handles container CPU quotas.") + case FeatureEventRecorder: + opts = append(opts, enableEventRecorder()) + logger.Warn("Experimental event recorder enabled") default: return nil, fmt.Errorf("unknown option '%s' for --enable-feature", feature) } @@ -169,10 +186,12 @@ func (n NoopFlags) EnableAlertNamesInMetrics() bool { return false } func (n NoopFlags) EnableReceiverNamesInMetrics() bool { return false } +func (n NoopFlags) EnableGroupKeyInMetrics() bool { return false } + func (n NoopFlags) ClassicMode() bool { return false } func (n NoopFlags) UTF8StrictMode() bool { return false } func (n NoopFlags) EnableAutoGOMEMLIMIT() bool { return false } -func (n NoopFlags) EnableAutoGOMAXPROCS() bool { return false } +func (n NoopFlags) EnableEventRecorder() bool { return false } diff --git a/vendor/github.com/prometheus/alertmanager/template/template.go b/vendor/github.com/prometheus/alertmanager/template/template.go index 587c3bbb469..73f1ac526ff 100644 --- a/vendor/github.com/prometheus/alertmanager/template/template.go +++ b/vendor/github.com/prometheus/alertmanager/template/template.go @@ -215,6 +215,7 @@ var DefaultFuncs = FuncMap{ } return t.In(loc), nil }, + "now": time.Now, "since": time.Since, "humanizeDuration": commonTemplates.HumanizeDuration, "toJson": func(v any) (string, error) { diff --git a/vendor/github.com/prometheus/alertmanager/types/types.go b/vendor/github.com/prometheus/alertmanager/types/types.go index b03be09c025..cd1f87f70a9 100644 --- a/vendor/github.com/prometheus/alertmanager/types/types.go +++ b/vendor/github.com/prometheus/alertmanager/types/types.go @@ -14,11 +14,6 @@ package types import ( - "sync" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/common/model" - "github.com/prometheus/alertmanager/alert" ) @@ -30,270 +25,3 @@ type AlertSlice = alert.AlertSlice // Deprecated: Use alert.Alerts directly. var Alerts = alert.Alerts - -// Deprecated: Use alert.AlertState constants directly. -type AlertState = alert.AlertState - -// Deprecated: Use alert.AlertStateActive directly. -const AlertStateActive AlertState = alert.AlertStateActive - -// Deprecated: Use alert.AlertStateSuppressed directly. -const AlertStateSuppressed AlertState = alert.AlertStateSuppressed - -// Deprecated: Use alert.AlertStateUnprocessed directly. -const AlertStateUnprocessed AlertState = alert.AlertStateUnprocessed - -// Deprecated: Use alert.AlertStatus directly. -type AlertStatus = alert.AlertStatus - -// groupStatus stores the state of the group, and, as applicable, the names -// of all active and mute time intervals that are muting it. -type groupStatus struct { - // mutedBy contains the names of all active and mute time intervals that - // are muting it. - mutedBy []string -} - -// AlertMarker helps to mark alerts as silenced and/or inhibited. -// All methods are goroutine-safe. -type AlertMarker interface { - // SetActiveOrSilenced replaces the previous SilencedBy by the provided IDs of - // active silences. The set of provided IDs is supposed to represent the - // complete set of relevant silences. If no active silence IDs are provided and - // InhibitedBy is already empty, it sets the provided alert to AlertStateActive. - // Otherwise, it sets the provided alert to AlertStateSuppressed. - SetActiveOrSilenced(alert model.Fingerprint, activeSilenceIDs []string) - // SetInhibited replaces the previous InhibitedBy by the provided IDs of - // alerts. In contrast to SetActiveOrSilenced, the set of provided IDs is not - // expected to represent the complete set of inhibiting alerts. (In - // practice, this method is only called with one or zero IDs. However, - // this expectation might change in the future. If no IDs are provided - // and InhibitedBy is already empty, it sets the provided alert to - // AlertStateActive. Otherwise, it sets the provided alert to - // AlertStateSuppressed. - SetInhibited(alert model.Fingerprint, alertIDs ...string) - - // Count alerts of the given state(s). With no state provided, count all - // alerts. - Count(...AlertState) int - - // Status of the given alert. - Status(model.Fingerprint) AlertStatus - // Delete the given alert. - Delete(...model.Fingerprint) - - // Various methods to inquire if the given alert is in a certain - // AlertState. Silenced also returns all the active silences, - // while Inhibited may return only a subset of inhibiting alerts. - Unprocessed(model.Fingerprint) bool - Active(model.Fingerprint) bool - Silenced(model.Fingerprint) (activeIDs []string, silenced bool) - Inhibited(model.Fingerprint) ([]string, bool) -} - -// GroupMarker helps to mark groups as active or muted. -// All methods are goroutine-safe. -// -// TODO(grobinson): routeID is used in Muted and SetMuted because groupKey -// is not unique (see #3817). Once groupKey uniqueness is fixed routeID can -// be removed from the GroupMarker interface. -type GroupMarker interface { - // Muted returns true if the group is muted, otherwise false. If the group - // is muted then it also returns the names of the time intervals that muted - // it. - Muted(routeID, groupKey string) ([]string, bool) - - // SetMuted marks the group as muted, and sets the names of the time - // intervals that mute it. If the list of names is nil or the empty slice - // then the muted marker is removed. - SetMuted(routeID, groupKey string, timeIntervalNames []string) - - // DeleteByGroupKey removes all markers for the GroupKey. - DeleteByGroupKey(routeID, groupKey string) -} - -// NewMarker returns an instance of a AlertMarker implementation. -func NewMarker(r prometheus.Registerer) *MemMarker { - m := &MemMarker{ - alerts: map[model.Fingerprint]*AlertStatus{}, - groups: map[string]*groupStatus{}, - } - m.registerMetrics(r) - return m -} - -type MemMarker struct { - alerts map[model.Fingerprint]*AlertStatus - groups map[string]*groupStatus - - mtx sync.RWMutex -} - -// Muted implements GroupMarker. -func (m *MemMarker) Muted(routeID, groupKey string) ([]string, bool) { - m.mtx.Lock() - defer m.mtx.Unlock() - status, ok := m.groups[routeID+groupKey] - if !ok { - return nil, false - } - return status.mutedBy, len(status.mutedBy) > 0 -} - -// SetMuted implements GroupMarker. -func (m *MemMarker) SetMuted(routeID, groupKey string, timeIntervalNames []string) { - m.mtx.Lock() - defer m.mtx.Unlock() - status, ok := m.groups[routeID+groupKey] - if !ok { - status = &groupStatus{} - m.groups[routeID+groupKey] = status - } - status.mutedBy = timeIntervalNames -} - -func (m *MemMarker) DeleteByGroupKey(routeID, groupKey string) { - m.mtx.Lock() - defer m.mtx.Unlock() - delete(m.groups, routeID+groupKey) -} - -func (m *MemMarker) registerMetrics(r prometheus.Registerer) { - newMarkedAlertMetricByState := func(st AlertState) prometheus.GaugeFunc { - return prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Name: "alertmanager_marked_alerts", - Help: "How many alerts by state are currently marked in the Alertmanager regardless of their expiry.", - ConstLabels: prometheus.Labels{"state": string(st)}, - }, - func() float64 { - return float64(m.Count(st)) - }, - ) - } - - alertsActive := newMarkedAlertMetricByState(AlertStateActive) - alertsSuppressed := newMarkedAlertMetricByState(AlertStateSuppressed) - alertStateUnprocessed := newMarkedAlertMetricByState(AlertStateUnprocessed) - - r.MustRegister(alertsActive) - r.MustRegister(alertsSuppressed) - r.MustRegister(alertStateUnprocessed) -} - -// Count implements AlertMarker. -func (m *MemMarker) Count(states ...AlertState) int { - m.mtx.RLock() - defer m.mtx.RUnlock() - - if len(states) == 0 { - return len(m.alerts) - } - - var count int - for _, status := range m.alerts { - for _, state := range states { - if status.State == state { - count++ - } - } - } - return count -} - -// SetActiveOrSilenced implements AlertMarker. -func (m *MemMarker) SetActiveOrSilenced(alert model.Fingerprint, activeIDs []string) { - m.mtx.Lock() - defer m.mtx.Unlock() - - s, found := m.alerts[alert] - if !found { - s = &AlertStatus{} - m.alerts[alert] = s - } - s.SilencedBy = activeIDs - - // If there are any silence or alert IDs associated with the - // fingerprint, it is suppressed. Otherwise, set it to - // AlertStateActive. - if len(activeIDs) == 0 && len(s.InhibitedBy) == 0 { - s.State = AlertStateActive - return - } - - s.State = AlertStateSuppressed -} - -// SetInhibited implements AlertMarker. -func (m *MemMarker) SetInhibited(alert model.Fingerprint, ids ...string) { - m.mtx.Lock() - defer m.mtx.Unlock() - - s, found := m.alerts[alert] - if !found { - s = &AlertStatus{} - m.alerts[alert] = s - } - s.InhibitedBy = ids - - // If there are any silence or alert IDs associated with the - // fingerprint, it is suppressed. Otherwise, set it to - // AlertStateActive. - if len(ids) == 0 && len(s.SilencedBy) == 0 { - s.State = AlertStateActive - return - } - - s.State = AlertStateSuppressed -} - -// Status implements AlertMarker. -func (m *MemMarker) Status(alert model.Fingerprint) AlertStatus { - m.mtx.RLock() - defer m.mtx.RUnlock() - - if s, found := m.alerts[alert]; found { - return *s - } - return AlertStatus{ - State: AlertStateUnprocessed, - SilencedBy: []string{}, - InhibitedBy: []string{}, - } -} - -// Delete implements AlertMarker. -func (m *MemMarker) Delete(alerts ...model.Fingerprint) { - m.mtx.Lock() - defer m.mtx.Unlock() - - for _, alert := range alerts { - delete(m.alerts, alert) - } -} - -// Unprocessed implements AlertMarker. -func (m *MemMarker) Unprocessed(alert model.Fingerprint) bool { - return m.Status(alert).State == AlertStateUnprocessed -} - -// Active implements AlertMarker. -func (m *MemMarker) Active(alert model.Fingerprint) bool { - return m.Status(alert).State == AlertStateActive -} - -// Inhibited implements AlertMarker. -func (m *MemMarker) Inhibited(alert model.Fingerprint) ([]string, bool) { - s := m.Status(alert) - return s.InhibitedBy, - s.State == AlertStateSuppressed && len(s.InhibitedBy) > 0 -} - -// Silenced returns whether the alert for the given Fingerprint is in the -// Silenced state, any associated silence IDs, and the silences state version -// the result is based on. -func (m *MemMarker) Silenced(alert model.Fingerprint) (activeIDs []string, silenced bool) { - s := m.Status(alert) - return s.SilencedBy, - s.State == AlertStateSuppressed && len(s.SilencedBy) > 0 -} diff --git a/vendor/go.etcd.io/etcd/api/v3/version/version.go b/vendor/go.etcd.io/etcd/api/v3/version/version.go index 5d748b563c5..b5382afb0b9 100644 --- a/vendor/go.etcd.io/etcd/api/v3/version/version.go +++ b/vendor/go.etcd.io/etcd/api/v3/version/version.go @@ -26,7 +26,7 @@ import ( var ( // MinClusterVersion is the min cluster version this etcd binary is compatible with. MinClusterVersion = "3.0.0" - Version = "3.6.11" + Version = "3.6.12" APIVersion = "unknown" // Git SHA Value will be set during build diff --git a/vendor/modules.txt b/vendor/modules.txt index 86e9d698c1f..0513c4b5d3b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -287,7 +287,7 @@ github.com/cenkalti/backoff # github.com/cenkalti/backoff/v5 v5.0.3 ## explicit; go 1.23 github.com/cenkalti/backoff/v5 -# github.com/ceph/go-ceph v0.39.0 +# github.com/ceph/go-ceph v0.40.0 ## explicit; go 1.25.0 github.com/ceph/go-ceph/cephfs github.com/ceph/go-ceph/cephfs/admin @@ -327,7 +327,7 @@ github.com/cloudflare/circl/math/mlsbset github.com/cloudflare/circl/sign github.com/cloudflare/circl/sign/ed25519 github.com/cloudflare/circl/sign/ed448 -# github.com/coreos/go-oidc/v3 v3.18.0 +# github.com/coreos/go-oidc/v3 v3.19.0 ## explicit; go 1.25.0 github.com/coreos/go-oidc/v3/oidc # github.com/coreos/go-semver v0.3.1 @@ -1030,7 +1030,7 @@ github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.23 ## explicit; go 1.20 github.com/mattn/go-runewidth -# github.com/mattn/go-sqlite3 v1.14.44 +# github.com/mattn/go-sqlite3 v1.14.47 ## explicit; go 1.21 github.com/mattn/go-sqlite3 # github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b @@ -1319,8 +1319,8 @@ github.com/orcaman/concurrent-map # github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 ## explicit; go 1.18 github.com/owncloud/libre-graph-api-go -# github.com/owncloud/reva/v2 v2.0.0-20260618144822-5723b763a8d4 -## explicit; go 1.25.7 +# github.com/owncloud/reva/v2 v2.0.0-20260622213237-e11912c5ad0b +## explicit; go 1.25.8 github.com/owncloud/reva/v2/cmd/revad/internal/grace github.com/owncloud/reva/v2/cmd/revad/runtime github.com/owncloud/reva/v2/internal/grpc/interceptors/appctx @@ -1700,8 +1700,8 @@ github.com/owncloud/reva/v2/tests/cs3mocks/mocks # github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c ## explicit; go 1.12 github.com/oxtoacart/bpool -# github.com/pablodz/inotifywaitgo v0.0.9 -## explicit; go 1.23.1 +# github.com/pablodz/inotifywaitgo v0.0.12 +## explicit; go 1.24.1 github.com/pablodz/inotifywaitgo/inotifywaitgo # github.com/patrickmn/go-cache v2.1.0+incompatible ## explicit @@ -1712,8 +1712,8 @@ github.com/pbnjay/memory # github.com/philhofer/fwd v1.2.0 ## explicit; go 1.20 github.com/philhofer/fwd -# github.com/pierrec/lz4/v4 v4.1.15 -## explicit; go 1.14 +# github.com/pierrec/lz4/v4 v4.1.26 +## explicit; go 1.17 github.com/pierrec/lz4/v4 github.com/pierrec/lz4/v4/internal/lz4block github.com/pierrec/lz4/v4/internal/lz4errors @@ -1737,7 +1737,7 @@ github.com/pmezard/go-difflib/difflib ## explicit; go 1.16 github.com/pquerna/cachecontrol github.com/pquerna/cachecontrol/cacheobject -# github.com/prometheus/alertmanager v0.32.1 +# github.com/prometheus/alertmanager v0.33.0 ## explicit; go 1.25.0 github.com/prometheus/alertmanager/alert github.com/prometheus/alertmanager/featurecontrol @@ -2089,7 +2089,7 @@ go.etcd.io/bbolt go.etcd.io/bbolt/errors go.etcd.io/bbolt/internal/common go.etcd.io/bbolt/internal/freelist -# go.etcd.io/etcd/api/v3 v3.6.11 +# go.etcd.io/etcd/api/v3 v3.6.12 ## explicit; go 1.25.0 go.etcd.io/etcd/api/v3/authpb go.etcd.io/etcd/api/v3/etcdserverpb @@ -2098,7 +2098,7 @@ go.etcd.io/etcd/api/v3/mvccpb go.etcd.io/etcd/api/v3/v3rpc/rpctypes go.etcd.io/etcd/api/v3/version go.etcd.io/etcd/api/v3/versionpb -# go.etcd.io/etcd/client/pkg/v3 v3.6.11 +# go.etcd.io/etcd/client/pkg/v3 v3.6.12 ## explicit; go 1.25.0 go.etcd.io/etcd/client/pkg/v3/fileutil go.etcd.io/etcd/client/pkg/v3/logutil @@ -2107,7 +2107,7 @@ go.etcd.io/etcd/client/pkg/v3/tlsutil go.etcd.io/etcd/client/pkg/v3/transport go.etcd.io/etcd/client/pkg/v3/types go.etcd.io/etcd/client/pkg/v3/verify -# go.etcd.io/etcd/client/v3 v3.6.11 +# go.etcd.io/etcd/client/v3 v3.6.12 ## explicit; go 1.25.0 go.etcd.io/etcd/client/v3 go.etcd.io/etcd/client/v3/credentials