Compare commits

..
Author SHA1 Message Date
Firas Frikha daf4d1b4db chore: bump reva to pick up the upload rollback deadlock fix 2026-08-04 11:34:39 +02:00
Firas Frikha 22994e6d6d chore: bump reva for rejected-overwrite fix 2026-08-03 14:38:42 +02:00
Firas Frikha 45474237d4 chore: bump reva for upload rollback fix 2026-08-03 13:27:43 +02:00
Firas Frikha 0968ff11e1 chore: bump reva for upload coordinator fixes 2026-08-03 11:10:54 +02:00
Firas Frikha 620a94abf9 chore: bump reva and pin etcd to 3.6.13 to keep go 1.25.11 2026-07-31 16:08:38 +02:00
Firas Frikha fe1c0b6316 fix: keep go directive at 1.25.11 2026-07-31 11:45:42 +02:00
Firas Frikha 69a8aee5e9 chore: bump reva for coordinator upload fixes 2026-07-31 11:13:55 +02:00
Firas Frikha 73f975ede5 fear: bump reva version 2026-07-31 09:54:58 +02:00
Firas Frikha a78bc828b8 fix: update reva version 2026-07-29 10:38:41 +02:00
Firas Frikha 6be26416f3 chore: bump reva version 2026-07-28 16:44:39 +02:00
Firas Frikha 1b7c258ffd chore: bump reva for ocm Delete fix and coordinator PUT groundwork 2026-07-28 15:44:41 +02:00
Firas Frikha 347cf8f1c1 chore: bump reva for ocm TouchFile fix 2026-07-28 15:09:39 +02:00
Firas Frikha b06db6ec8f chore: bump reva for ocm GetLock fix 2026-07-28 14:32:02 +02:00
Firas Frikha 870a0ad3f5 fix: fix go.mod file 2026-07-28 13:24:05 +02:00
Firas Frikha 520326c9ed feat: bump reva version 2026-07-28 11:57:22 +02:00
Prajwol Amatya 91f0671153 [tests-only] test: add test to copy resources from drive to vault and from vault to drive (#12576)
test: add test to copy resources from drive to vault and vice versa

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-07-28 14:23:42 +05:45
Gaurav Soni 898f89c697 fix(admin-settings): prevent deleting your own account (#12657)
In the user management, the account you are currently logged in as could
be selected and included in a delete action, even though the backend
always rejects self-deletion. Deleting a selection that included your own
account produced a "Failed to delete 1 user" error and made your own row
temporarily disappear from the list until the page was refreshed.

The delete action now excludes the current user from the request, so all
other selected users are deleted while your own account is left
untouched. When your own account is part of the selection, the delete
confirmation dialog shows a hint that it will not be deleted.
2026-07-27 16:04:11 +02:00
Matteo b708076e67 enhancement(web): [OCISDEV-1085] add undo action to delete notification (#12650)
feat(web): [OCISDEV-1085] add undo action to delete notification

Adds an "Undo" action to the delete success toast so users can restore
deleted resources without navigating to the trash bin, plus a Ctrl+Z/Cmd+Z
shortcut that triggers the same restore while the notification is visible.
2026-07-27 13:42:15 +02:00
Juan Pablo Villafañez 8dc7afc07c [OCISDEV-969] fix: ocis_multi deployment with proper ldap groups (#12466)
fix: ocis_multi deployment with proper ldap groups
2026-07-27 11:13:39 +02:00
Matteo 7dcc74c3dd fix(idp): announce sign-in errors and fix keyboard use (#12649) 2026-07-27 08:22:44 +00:00
Matteo e70497b49c chore: update brace expansion package (#12653) 2026-07-27 09:22:24 +02:00
Matteo b395d08db6 fix(web): remove unneeded keyboard focus stops (#12645)
Icons and date columns in tables received keyboard focus without
triggering any action, and the contextual helper icon duplicated its
button's label.
2026-07-24 22:57:51 +02:00
Matteo 1d16dd9e1e fix(web): focus New/Upload dropdown menus on open (#12646)
The New and Upload button dropdowns did not receive focus when opened,
so arrow key navigation between menu items didn't work, unlike the
context menu.
2026-07-24 22:50:02 +02:00
Michal Klos 86fa96362a feat: [OCISDEV-855] receivedsharecache: retry on transient storage errors in CAS loop (#12621) 2026-07-24 19:43:46 +02:00
Matteo f005d68eae fix(web): stop breadcrumb items from being announced twice (#12643)
Each breadcrumb list item had tabindex="0", putting it in the
keyboard/screen reader focus order alongside the link or button
nested inside it, causing every segment to be announced twice.
2026-07-24 12:23:56 +02:00
Matteo d68b53c6d8 chore: improve theme color contrast (#12642) 2026-07-24 11:29:55 +02:00
Matteo f8b861c723 enhancement(web): show select-all checkbox label in tile view (#12640)
feat(web): show select-all checkbox label in tile view

Make the select-all checkbox label visible in the tile view to match
the list view and make the checkbox's purpose clear.
2026-07-24 11:29:49 +02:00
Matteo 8b675b2e51 fix(web): improve contrast of form controls in dark and vault themes (#12639)
Fixes low-contrast sliders, switches, select highlights, and the global
search input/placeholder, including an !important override that blocked
theme-specific search colors and an invalid CSS var() fallback.
2026-07-24 11:29:37 +02:00
Firas Frikha 34b2b14171 fix: parentPath in session 2026-07-23 16:55:02 +02:00
kobergjandClaude Opus 4.8 9f72d77bfc fix(graph): [OCISDEV-751] return correct issuerAssignedId on /me (#12431)
The /graph/v1.0/me endpoint reported the internal user UUID as
identities[].issuerAssignedId instead of the OIDC sub. The fast path
built the user model from the CS3 context user, which does not carry the
external identity. /me now always resolves the user through the identity
backend; group memberships are still only expanded on $expand=memberOf.

Forward-port of #12411 to master.

Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:37:09 +02:00
Matteo 30009ff770 enhancement(web): add missing main/footer regions and fix skip-to-main link (#12637)
feat: add missing main/footer regions and fix skip-to-main link

Add missing main and footer elements to the 404, private/public link
resolving, missing-config, logout, and access-denied pages, and fix the
skip-to-main link which silently did nothing on plain-layout pages due
to a missing target id and a stale cached DOM reference.
2026-07-23 14:08:21 +00:00
Firas Frikha d5165c7e48 fix: update config file 2026-07-23 14:19:47 +02:00
Matteo 50141f471b fix(web): preserve focus in file versions sidebar (#12630)
- Keep keyboard and screen-reader focus inside the versions sidebar while panels transition or reload.
- Restore focus to the opening control when the sidebar closes and to the matching Restore action after a version is restored.
- Improve version date and action announcements without introducing duplicate announcements or additional tab stops.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-07-23 13:44:02 +02:00
dependabot[bot] d65f3fc215 build(deps): bump the minor-and-patch group across 1 directory with 12 updates (#12607)
Bumps the minor-and-patch group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [github.com/beevik/etree](https://github.com/beevik/etree) | `1.6.0` | `1.7.0` |
| [github.com/coreos/go-oidc/v3](https://github.com/coreos/go-oidc) | `3.19.0` | `3.20.0` |
| [github.com/go-chi/chi/v5](https://github.com/go-chi/chi) | `5.3.0` | `5.3.1` |
| [github.com/go-ldap/ldap/v3](https://github.com/go-ldap/ldap) | `3.4.13` | `3.4.14` |
| [github.com/kovidgoyal/imaging](https://github.com/kovidgoyal/imaging) | `1.8.22` | `1.8.23` |
| [google.golang.org/grpc](https://github.com/grpc/grpc-go) | `1.82.0` | `1.82.1` |



Updates `github.com/beevik/etree` from 1.6.0 to 1.7.0
- [Release notes](https://github.com/beevik/etree/releases)
- [Changelog](https://github.com/beevik/etree/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/beevik/etree/compare/v1.6.0...v1.7.0)

Updates `github.com/coreos/go-oidc/v3` from 3.19.0 to 3.20.0
- [Release notes](https://github.com/coreos/go-oidc/releases)
- [Commits](https://github.com/coreos/go-oidc/compare/v3.19.0...v3.20.0)

Updates `github.com/go-chi/chi/v5` from 5.3.0 to 5.3.1
- [Release notes](https://github.com/go-chi/chi/releases)
- [Changelog](https://github.com/go-chi/chi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/go-chi/chi/compare/v5.3.0...v5.3.1)

Updates `github.com/go-ldap/ldap/v3` from 3.4.13 to 3.4.14
- [Release notes](https://github.com/go-ldap/ldap/releases)
- [Commits](https://github.com/go-ldap/ldap/compare/v3.4.13...v3.4.14)

Updates `github.com/kovidgoyal/imaging` from 1.8.22 to 1.8.23
- [Release notes](https://github.com/kovidgoyal/imaging/releases)
- [Commits](https://github.com/kovidgoyal/imaging/compare/v1.8.22...v1.8.23)

Updates `golang.org/x/crypto` from 0.53.0 to 0.54.0
- [Commits](https://github.com/golang/crypto/compare/v0.53.0...v0.54.0)

Updates `golang.org/x/image` from 0.43.0 to 0.44.0
- [Commits](https://github.com/golang/image/compare/v0.43.0...v0.44.0)

Updates `golang.org/x/net` from 0.56.0 to 0.57.0
- [Commits](https://github.com/golang/net/compare/v0.56.0...v0.57.0)

Updates `golang.org/x/sync` from 0.21.0 to 0.22.0
- [Commits](https://github.com/golang/sync/compare/v0.21.0...v0.22.0)

Updates `golang.org/x/term` from 0.44.0 to 0.45.0
- [Commits](https://github.com/golang/term/compare/v0.44.0...v0.45.0)

Updates `golang.org/x/text` from 0.38.0 to 0.40.0
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.38.0...v0.40.0)

Updates `google.golang.org/grpc` from 1.82.0 to 1.82.1
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.82.0...v1.82.1)

---
updated-dependencies:
- dependency-name: github.com/beevik/etree
  dependency-version: 1.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/coreos/go-oidc/v3
  dependency-version: 3.20.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/go-chi/chi/v5
  dependency-version: 5.3.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/go-ldap/ldap/v3
  dependency-version: 3.4.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/kovidgoyal/imaging
  dependency-version: 1.8.23
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/crypto
  dependency-version: 0.54.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/image
  dependency-version: 0.44.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/net
  dependency-version: 0.57.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/sync
  dependency-version: 0.22.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/term
  dependency-version: 0.45.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/text
  dependency-version: 0.40.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: google.golang.org/grpc
  dependency-version: 1.82.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-22 08:19:45 +00:00
Firas Frikha 26fa954329 chore: bump reva version 2026-07-20 14:14:58 +02:00
228 changed files with 11011 additions and 2416 deletions

No files matched your search

+6
View File
@@ -4,3 +4,9 @@
CVE-2026-32284 # github.com/shamaton/msgpack/v2 v2.4.0 — no fix available upstream
vendor/github.com/crewjam/saml/xmlenc/fuzz.go # test RSA key used in fuzz corpus, not a real secret
# web frontend transitive dependencies, both pulled in via the pnpm overrides in
# web/package.json. Published after the last lockfile refresh, so every branch
# fails on them. Drop these once the overrides are bumped upstream.
CVE-2026-69152 # brace-expansion 5.0.8 — fix in 5.0.9
CVE-2026-18446 # fast-uri 3.1.4 — fix in 3.1.5
@@ -0,0 +1,15 @@
Bugfix: Prevent deleting your own account in the user management
In the admin settings user management, the account you are currently logged in
as could be selected and included in a delete action, even though the backend
always rejects self-deletion. Deleting a selection that included your own
account produced a "Failed to delete 1 user" error and made your own row
temporarily disappear from the list until the page was refreshed.
The delete action now excludes the current user from the request, so all other
selected users are deleted while your own account is left untouched. When your
own account is part of the selection, the delete confirmation dialog shows a
hint that it will not be deleted.
https://github.com/owncloud/ocis/pull/12657
https://github.com/owncloud/ocis/issues/12582
@@ -0,0 +1,10 @@
Bugfix: Stop breadcrumb items from being announced twice
Each breadcrumb list item had `tabindex="0"`, putting the item itself in the
keyboard/screen reader focus order in addition to the link or button nested
inside it. This caused every breadcrumb segment to be announced twice in a
row. The list item is no longer a separate focus stop; only its inner link
or button is, while the item remains focusable enough for existing
drag-and-drop styling to keep working.
https://github.com/owncloud/ocis/pull/12643
@@ -0,0 +1,12 @@
Bugfix: Announce IDP sign-in errors and fix keyboard use
The login, consent, and account chooser pages did not announce error
messages when they appeared, and invalid username/password fields gave no
indication of their error state. The consent screen's scope list also had no
programmatic link between each entry and its checkbox, and the account
chooser's "continue as" and "use another account" entries could not be
reached or activated with a keyboard. A visible focus outline on the login
form's input fields had also been removed with no replacement. All of these
have been fixed.
https://github.com/owncloud/ocis/pull/12649
@@ -0,0 +1,28 @@
Bugfix: Fix low-contrast form controls in dark and vault themes
Several form controls were hard to see against dark and vault theme
backgrounds. The view-options range slider had no visible track border and
relied on an opacity dip on hover, making it barely visible at rest. The
switch component's off-state track and thumb, and its on-state thumb, used
colors too close to their surrounding background to read as a toggle. The
select combobox's highlighted/selected option text used a color too close to
the highlight background.
The global search input's text color was forced with `!important`,
overriding the theme-specific search text color some themes set, which made
typed text render in white on a white search input background in the vault
"Dark Theme – High Contrast". The search placeholder color also used an
invalid CSS custom property fallback (a bare property name instead of a
nested `var()`), silently breaking the placeholder color for any theme that
didn't define a search-specific placeholder token, and the vault "Dark
Theme"'s placeholder color was too close to its input's text and border color
to read as muted.
The slider now has a visible border and no longer dims on rest, the switch
and select now use colors with sufficient contrast against their
backgrounds, the `!important` override blocking theme-specific search colors
has been removed, the invalid placeholder fallback has been fixed, and the
vault "Dark Theme" placeholder color has been changed to one with visible
contrast against the input text.
https://github.com/owncloud/ocis/pull/12639
@@ -0,0 +1,9 @@
Bugfix: Fix keyboard navigation in "New" and "Upload" dropdown menus
Opening the "New" or "Upload" dropdown menu in the Files app toolbar did
not move focus into the menu, so pressing the arrow keys had no effect
on the highlighted item, unlike the existing right-click context menu.
Both dropdowns now focus their first item on open, restoring arrow key
navigation.
https://github.com/owncloud/ocis/pull/12646
@@ -0,0 +1,10 @@
Bugfix: Remove unneeded keyboard focus stops
Some icons and date columns in tables (spaces list, file list) could
unexpectedly receive keyboard focus even though they don't trigger any
action, adding unnecessary stops when tabbing through the page. The
contextual helper icon also carried a label that duplicated the label
already present on its surrounding button. These redundant focus stops
and duplicate labels have been removed.
https://github.com/owncloud/ocis/pull/12645
@@ -0,0 +1,9 @@
Bugfix: Fix share metadata corruption during concurrent share operations
When multiple sharing service replicas processed share operations concurrently
for the same user, the share metadata could become corrupted with references to
missing data, making all shares inaccessible to that user. The received share
cache now uses compare-and-swap (etag) validation to detect concurrent writes
and retries gracefully, preventing metadata corruption.
https://github.com/owncloud/ocis/pull/12621
@@ -0,0 +1,12 @@
Bugfix: Preserve accessibility focus in the file versions sidebar
Opening the file versions panel with a keyboard or screen reader could move
focus to the main page, and restoring a version could briefly move focus to the
main page before selecting the sidebar's back button. The sidebar now manages
focus throughout panel transitions and loading states, restores focus to the
control that opened it when closed, and returns focus to the restored version's
Restore button after the operation completes. Version dates and action labels
also provide clearer context for screen reader users without duplicate
announcements or additional tab stops.
https://github.com/owncloud/ocis/pull/12630
@@ -0,0 +1,10 @@
Enhancement: Improve page structure on several pages
We've added missing `main` and `footer` regions to several pages (404,
private link resolving, missing config, logout, access denied, public link
resolving) for a more consistent page structure. We've also fixed the
"Skip to main" link, which previously did nothing on pages using the plain
layout (login, logout, public/private link pages) due to a missing target id
and a stale cached DOM reference.
https://github.com/owncloud/ocis/pull/12637
@@ -0,0 +1,7 @@
Enhancement: Show the select-all checkbox label in tile view
The label of the select-all checkbox in the resource tiles view is now
visible, improving the user experience by making it clear what the
checkbox is for.
https://github.com/owncloud/ocis/pull/12640
@@ -0,0 +1,12 @@
Enhancement: Add "Undo" action to the delete success notification
Deleting a file or folder now shows an "Undo" action alongside the
"moved to trash bin" notification, letting users restore the deleted
resources directly from the toast instead of navigating to the trash
bin. The action is only shown when the resources can be resolved in
the trash and the space supports restoring from it. The notification
pauses its auto-dismiss timer while hovered or focused, so it does not
disappear before the action can be used. Pressing Ctrl+Z (or Cmd+Z on
macOS) while the notification is visible triggers the same undo.
https://github.com/owncloud/ocis/pull/12650
@@ -0,0 +1,13 @@
Bugfix: Return correct issuerAssignedId on /me
The `/graph/v1.0/me` endpoint reported the internal user UUID as
`identities[].issuerAssignedId` instead of the issuer-assigned identity (the
OIDC `sub`). The endpoint took a fast path that built the user model from the
CS3 user in the request context, which does not carry the external identity, so
it fell back to the internal UUID. `/me` now always resolves the user through
the identity backend, which reads the stored external identity and returns the
correct value. Group memberships are still only expanded when
`$expand=memberOf` is requested.
https://github.com/owncloud/ocis/pull/12431
https://github.com/owncloud/ocis/pull/12411
@@ -2,7 +2,7 @@
printenv
# replace oCIS domain in keycloak realm import
mkdir /opt/keycloak/data/import
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
sed -e "s/ocis.owncloud.test/${OCIS_DOMAIN}/g" -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
# sed -e "s/ocis.ocm.owncloud.test/${OCIS_OCM_DOMAIN}/g" /opt/keycloak/data/import-dist/ocis-realm.json > /opt/keycloak/data/import/oCIS-realm.json
# run original docker-entrypoint
@@ -192,7 +192,8 @@ services:
OCIS_LDAP_BIND_PASSWORD: ${LDAP_ADMIN_PASSWORD:-admin}
OCIS_LDAP_GROUP_BASE_DN: "ou=groups,dc=owncloud,dc=com"
GRAPH_LDAP_GROUP_CREATE_BASE_DN: "ou=groups-8d24cb5f-6ee6-4b98-86df-c4c268dddb46,ou=groups,dc=owncloud,dc=com"
OCIS_LDAP_GROUP_OBJECTCLASS: "owncloudGroup"
OCIS_LDAP_GROUP_OBJECTCLASS: "groupOfNames"
OCIS_LDAP_GROUP_ADDITIONAL_OBJECTCLASSES: "ownCloudGroup"
OCIS_LDAP_USER_BASE_DN: "ou=users,dc=owncloud,dc=com"
OCIS_LDAP_USER_OBJECTCLASS: "inetOrgPerson"
LDAP_LOGIN_ATTRIBUTES: "uid"
@@ -272,6 +273,7 @@ services:
- "./config/keycloak/ocis-realm.dist.json:/opt/keycloak/data/import-dist/ocis-realm.json"
environment:
OCIS_DOMAIN: ${OCIS_DOMAIN:-ocis.owncloud.test}
OCIS_OCM_DOMAIN: ${OCIS_OCM_DOMAIN:-ocis.ocm.owncloud.test}
KC_HOSTNAME: ${KEYCLOAK_DOMAIN:-keycloak.owncloud.test}
KC_DB: postgres
KC_DB_URL: "jdbc:postgresql://postgres:5432/keycloak"
+8 -8
View File
@@ -66,10 +66,10 @@ require (
github.com/open-policy-agent/opa v1.18.2
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-20260710104539-1f85e04c1e35
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.23.2
github.com/prometheus/client_golang v1.24.1
github.com/r3labs/sse/v2 v2.10.0
github.com/rogpeppe/go-internal v1.15.0
github.com/rs/cors v1.11.1
@@ -240,7 +240,7 @@ require (
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect
github.com/juliangruber/go-intersect v1.1.0 // indirect
github.com/kevinburke/ssh_config v1.2.0 // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/klauspost/compress v1.19.1 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
@@ -260,7 +260,7 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mattn/go-sqlite3 v1.14.47 // indirect
github.com/mattn/go-sqlite3 v1.14.48 // indirect
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect
github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect
github.com/miekg/dns v1.1.72 // indirect
@@ -295,8 +295,8 @@ require (
github.com/pquerna/cachecontrol v0.2.0 // indirect
github.com/prometheus/alertmanager v0.33.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/prometheus/statsd_exporter v0.22.8 // indirect
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
github.com/rs/xid v1.6.0 // indirect
@@ -308,7 +308,7 @@ require (
github.com/segmentio/ksuid v1.0.4 // indirect
github.com/sercand/kuberesolver/v5 v5.1.1 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/sethvargo/go-password v0.3.1 // indirect
github.com/sethvargo/go-password v0.4.0 // indirect
github.com/skeema/knownhosts v1.3.1 // indirect
github.com/spacewander/go-suffix-tree v0.0.0-20191010040751-0865e368c784 // indirect
github.com/spf13/pflag v1.0.10 // indirect
@@ -338,7 +338,7 @@ require (
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.37.0 // indirect
+24 -16
View File
@@ -576,8 +576,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
@@ -652,8 +652,8 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/mattn/go-sqlite3 v1.14.48 h1:7XHIgl0a8HwOaiK4E47ozLkST78rR9+OtNGx27D/TFs=
github.com/mattn/go-sqlite3 v1.14.48/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=
@@ -739,8 +739,16 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35 h1:40KHez6z6Ea+MHatRfZp4ZTX1TASGRG5UfvOpsQRbgU=
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35/go.mod h1:m2fGRZDsnNSBszbnwysuq7uhlitQ90+weX4FFQRdkak=
github.com/owncloud/reva/v2 v2.0.0-20260731133734-ff71861a97b3 h1:cx509Tm9QnYvf5OCQs4jwMZgTVMMUjFiVcKmGzmP/r0=
github.com/owncloud/reva/v2 v2.0.0-20260731133734-ff71861a97b3/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
github.com/owncloud/reva/v2 v2.0.0-20260803085958-0f1033fbf237 h1:6EInmwSbEg91zdXQ65/uz21gwC3ZZ9VxlBqpRgT/w3U=
github.com/owncloud/reva/v2 v2.0.0-20260803085958-0f1033fbf237/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
github.com/owncloud/reva/v2 v2.0.0-20260803112253-6c2f84027dda h1:rg+J1SmPVCnt174ytaZHydtHfUyJ9AomdrADpL7dELo=
github.com/owncloud/reva/v2 v2.0.0-20260803112253-6c2f84027dda/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
github.com/owncloud/reva/v2 v2.0.0-20260803123448-40f303ed2d94 h1:Dau8BtnYwOlDJWx0dw3Kz2tcbricrbMIxFsaU32cc1k=
github.com/owncloud/reva/v2 v2.0.0-20260803123448-40f303ed2d94/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c h1:m3HzDJsnHEKcR4J4M/+Al8hSRG8uw35CI3zS7GZx9Nc=
github.com/owncloud/reva/v2 v2.0.0-20260804082450-45ec3bf8ba7c/go.mod h1:bW0gOn58J6J9sWQDdWP5oQhCjTKoEGAxT4tWE6Ztziw=
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.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
@@ -780,8 +788,8 @@ github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqr
github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
github.com/prometheus/client_golang v1.12.2/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.0.0-20170216185247-6f3806018612/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
@@ -796,8 +804,8 @@ github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9
github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
github.com/prometheus/common v0.35.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.0.0-20170703101242-e645f4e5aaa8/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
@@ -805,8 +813,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4=
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/prometheus/statsd_exporter v0.22.7/go.mod h1:N/TevpjkIh9ccs6nuzY3jQn9dFqnUakOjnEuMPJJJnI=
github.com/prometheus/statsd_exporter v0.22.8 h1:Qo2D9ZzaQG+id9i5NYNGmbf1aa/KxKbB9aKfMS+Yib0=
github.com/prometheus/statsd_exporter v0.22.8/go.mod h1:/DzwbTEaFTE0Ojz5PqcSk6+PFHOPWGxdXVr6yC8eFOM=
@@ -839,8 +847,8 @@ github.com/sercand/kuberesolver/v5 v5.1.1 h1:CYH+d67G0sGBj7q5wLK61yzqJJ8gLLC8aep
github.com/sercand/kuberesolver/v5 v5.1.1/go.mod h1:Fs1KbKhVRnB2aDWN12NjKCB+RgYMWZJ294T3BtmVCpQ=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-password v0.3.1 h1:WqrLTjo7X6AcVYfC6R7GtSyuUQR9hGyAj/f1PYQZCJU=
github.com/sethvargo/go-password v0.3.1/go.mod h1:rXofC1zT54N7R8K/h1WDUdkf9BOx5OptoxrMBcrXzvs=
github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD2GWLVU=
github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
github.com/shamaton/msgpack/v2 v2.4.1 h1:JtJ141QoQ3NqgPDsjq2v9VXlaON8SiQOwEaoNLEK/MQ=
github.com/shamaton/msgpack/v2 v2.4.1/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
@@ -998,8 +1006,8 @@ go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9i
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+16 -16
View File
@@ -62,22 +62,22 @@ func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) {
return
}
var me *libregraph.User
// We can just return the user from context unless we need to expand the group memberships
if !slices.Contains(exp, "memberOf") {
me = identity.CreateUserModelFromCS3(u)
} else {
var err error
logger.Debug().Msg("calling get user on backend")
me, err = g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
if err != nil {
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
errorcode.RenderError(w, r, err)
return
}
if me.MemberOf == nil {
me.MemberOf = []libregraph.Group{}
}
// Always resolve the user through the identity backend. The CS3 user from
// the request context does not carry the issuer-assigned identity (OIDC
// sub), so building the model from it (CreateUserModelFromCS3) would report
// the internal user UUID as identities[].issuerAssignedId. The backend reads
// the stored external identity and returns the correct value. Group
// memberships are only expanded (and thus only queried) when $expand=memberOf
// is requested, so the extra cost here is a single user lookup.
logger.Debug().Msg("calling get user on backend")
me, err := g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
if err != nil {
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
errorcode.RenderError(w, r, err)
return
}
if slices.Contains(exp, "memberOf") && me.MemberOf == nil {
me.MemberOf = []libregraph.Group{}
}
// expand appRoleAssignments if requested
@@ -115,6 +115,16 @@ var _ = Describe("Users", func() {
})
It("gets the information", func() {
user := &libregraph.User{
Id: libregraph.PtrString("user"),
Identities: []libregraph.ObjectIdentity{
{
Issuer: libregraph.PtrString("https://idp.example.com"),
IssuerAssignedId: libregraph.PtrString("the-oidc-sub"),
},
},
}
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
Return(&settings.GetValueResponse{
Value: &settingsmsg.ValueWithIdentifier{
@@ -139,6 +149,19 @@ var _ = Describe("Users", func() {
svc.GetMe(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
data, err := io.ReadAll(rr.Body)
Expect(err).ToNot(HaveOccurred())
responseUser := &libregraph.User{}
err = json.Unmarshal(data, &responseUser)
Expect(err).ToNot(HaveOccurred())
// The identity (issuerAssignedId, the OIDC sub) must come from the
// backend, not be fabricated from the internal user UUID. See
// OCISDEV-751.
Expect(responseUser.GetIdentities()).To(HaveLen(1))
Expect(responseUser.GetIdentities()[0].GetIssuerAssignedId()).To(Equal("the-oidc-sub"))
})
It("expands the memberOf", func() {
@@ -193,6 +216,10 @@ var _ = Describe("Users", func() {
RoleId: "some-appRole-ID",
},
}
user := &libregraph.User{
Id: libregraph.PtrString("user"),
}
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, nil)
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
Return(&settings.GetValueResponse{
@@ -14,16 +14,16 @@
<div class="oc-login-form" id="chooseaccount-root">
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p id="oc-chooseaccount-error" class="oc-error-message" hidden></p>
<p id="oc-chooseaccount-error" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
<div id="chooseaccount-body" hidden>
<p class="oc-light oc-consent-headline" id="chooseaccount-title">{{.HeadlineSub}}</p>
<ul class="oc-consent-scopes" id="account-list">
<li class="oc-chooseaccount-item" id="item-current">
<span class="oc-chooseaccount-avatar" id="avatar-current"></span>
<li class="oc-chooseaccount-item" id="item-current" role="button" tabindex="0">
<span class="oc-chooseaccount-avatar" id="avatar-current" aria-hidden="true"></span>
<span class="oc-light oc-chooseaccount-label" id="label-current"></span>
</li>
<li class="oc-chooseaccount-item" id="item-other">
<span class="oc-chooseaccount-avatar">?</span>
<li class="oc-chooseaccount-item" id="item-other" role="button" tabindex="0">
<span class="oc-chooseaccount-avatar" aria-hidden="true">?</span>
<span class="oc-light oc-chooseaccount-label">{{.UseAnotherLabel}}</span>
</li>
</ul>
@@ -77,6 +77,15 @@
catch (_) { return false; }
}
function onKeyActivate(el, handler) {
el.addEventListener("keydown", function(e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handler();
}
});
}
var helloReq = {
state: qs("state"),
flow: qs("flow") || "oidc",
@@ -106,7 +115,7 @@
bodyEl.hidden = false;
// "Continue as current user" — mode=0 logon (cookie re-auth, no password)
itemCurrent.addEventListener("click", function() {
function activateCurrent() {
itemCurrent.style.opacity = "0.5";
itemOther.style.pointerEvents = "none";
fetchApi("/_/logon", { state: helloReq.state, params: [data.username, "", "0"], hello: helloReq })
@@ -133,14 +142,16 @@
resetSignInState();
})
.catch(resetSignInState);
});
}
itemCurrent.addEventListener("click", activateCurrent);
onKeyActivate(itemCurrent, activateCurrent);
})
.catch(function() {
window.location.href = pathPrefix + '/identifier' + window.location.search;
});
// "Use another account" — invalidate current session then go to login form
itemOther.addEventListener("click", function() {
function activateOther() {
var loginParams = new URLSearchParams(window.location.search);
loginParams.set("prompt", "login");
loginParams.delete("flow");
@@ -148,7 +159,9 @@
fetchApi("/_/logoff", { state: helloReq.state }).then(function() {
window.location.href = target;
});
});
}
itemOther.addEventListener("click", activateOther);
onKeyActivate(itemOther, activateOther);
})();
</script>
</body>
+5 -2
View File
@@ -14,7 +14,7 @@
<div class="oc-login-form" id="consent-root">
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p id="oc-consent-error-message" class="oc-error-message" hidden></p>
<p id="oc-consent-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
<div id="consent-body" hidden>
<p id="consent-display-name" class="oc-light oc-consent-headline"></p>
<p id="consent-username" class="oc-light oc-consent-username"></p>
@@ -127,13 +127,16 @@
if (!desc) desc = "Scope: " + scope;
var li = document.createElement("li");
li.className = "oc-consent-scope-item";
var scopeId = "consent-scope-" + alias;
var cb = document.createElement("input");
cb.type = "checkbox";
cb.id = scopeId;
cb.checked = true;
cb.disabled = true;
cb.className = "oc-consent-checkbox";
var label = document.createElement("span");
var label = document.createElement("label");
label.className = "oc-light";
label.setAttribute("for", scopeId);
label.textContent = desc;
li.appendChild(cb);
li.appendChild(label);
+1 -1
View File
@@ -14,8 +14,8 @@
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p class="oc-message">{{.Message}}</p>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</body>
</html>
+7 -3
View File
@@ -23,12 +23,12 @@
data-msg-sign-in="{{.ButtonSignIn}}">
<div>
<label class="oc-label" for="oc-login-username">{{.LabelUsername}}</label>
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" required>
<input class="oc-input" type="text" id="oc-login-username" name="username" autocomplete="username" placeholder="{{.LabelUsername}}" aria-describedby="oc-login-error-message" required>
</div>
<div>
<label class="oc-label" for="oc-login-password">{{.LabelPassword}}</label>
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" required>
<p id="oc-login-error-message" class="oc-error-message" hidden></p>
<input class="oc-input" type="password" id="oc-login-password" name="password" autocomplete="current-password" placeholder="{{.LabelPassword}}" aria-describedby="oc-login-error-message" required>
<p id="oc-login-error-message" class="oc-error-message" role="alert" aria-live="assertive" hidden></p>
</div>
<div>
<button class="oc-button-primary" type="submit" id="submit-btn">{{.ButtonSignIn}}</button>
@@ -103,12 +103,16 @@
errorEl.hidden = false;
usernameEl.classList.add("error");
passwordEl.classList.add("error");
usernameEl.setAttribute("aria-invalid", "true");
passwordEl.setAttribute("aria-invalid", "true");
}
function hideError() {
errorEl.hidden = true;
usernameEl.classList.remove("error");
passwordEl.classList.remove("error");
usernameEl.removeAttribute("aria-invalid");
passwordEl.removeAttribute("aria-invalid");
}
function setLoading(loading) {
@@ -297,10 +297,19 @@ main {
}
.oc-input:focus {
outline: none;
outline: 2px solid #00b3f0;
outline-offset: 1px;
border: 1px solid #fff;
}
.oc-chooseaccount-item:focus-visible,
.oc-button-primary:focus-visible,
.oc-button-cancel:focus-visible,
.oc-button-consent:focus-visible {
outline: 2px solid #00b3f0;
outline-offset: 2px;
}
.oc-button-primary {
display: block;
width: 100%;
+1 -1
View File
@@ -14,8 +14,8 @@
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<p class="oc-message">{{.Message}}</p>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</body>
</html>
+12 -8
View File
@@ -91,8 +91,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
"service_account_secret": cfg.ServiceAccount.Secret,
},
"dataprovider": map[string]interface{}{
"prefix": "data",
"driver": "ocmreceived",
"prefix": "data",
"driver": "ocmreceived",
"upload_directory": cfg.OCMStorageProvider.StorageRoot,
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
@@ -157,9 +158,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
"file": cfg.OCMShareProvider.Drivers.JSON.File,
},
},
"gatewaysvc": cfg.Reva.Address,
"provider_domain": providerDomain,
"webdav_endpoint": cfg.Commons.OcisURL,
"gatewaysvc": cfg.Reva.Address,
"provider_domain": providerDomain,
"webdav_endpoint": cfg.Commons.OcisURL,
"webapp_template": cfg.OCMShareProvider.WebappTemplate,
"client_insecure": cfg.OCMShareProvider.Insecure,
"enable_user_sharing": cfg.OCMShareProvider.EnableUserSharing,
@@ -181,11 +182,14 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
},
},
"storageprovider": map[string]interface{}{
"driver": "ocmreceived",
"driver": "ocmreceived",
"upload_directory": cfg.OCMStorageProvider.StorageRoot,
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
"storage_root": cfg.OCMStorageProvider.StorageRoot,
"insecure": cfg.OCMStorageProvider.Insecure,
"storage_root": cfg.OCMStorageProvider.StorageRoot,
"service_account_id": cfg.ServiceAccount.ID,
"service_account_secret": cfg.ServiceAccount.Secret,
},
},
"data_server_url": cfg.OCMStorageProvider.DataServerURL,
@@ -379,8 +379,8 @@
"swatch-passive-hover-outline": "#F7D496",
"swatch-passive-muted": "#99bae0",
"swatch-passive-contrast": "#000000",
"swatch-primary-default": "#F0AA39",
"swatch-primary-hover": "#CA912B",
"swatch-primary-default": "#9C6B00",
"swatch-primary-hover": "#6C4500",
"swatch-primary-muted": "#F0AA39",
"swatch-primary-muted-hover": "#CA912B",
"swatch-primary-gradient": "#F0AA39",
@@ -500,8 +500,8 @@
"input-bg": "#000000",
"input-border": "#ffffff",
"input-text-default": "#ffffff",
"input-text-muted": "#f8f8f8",
"search-input-text-muted": "#f8f8f8",
"input-text-muted": "#bdbfc3",
"search-input-text-muted": "#bdbfc3",
"swatch-brand-default": "#191A25",
"swatch-brand-hover": "#ffffff",
"swatch-brand-contrast": "#F0AA39",
BIN
View File
Binary file not shown.
+121 -16
View File
@@ -384,6 +384,7 @@ class SpacesContext implements Context {
* @param string $spaceName
* @param string $fileName
* @param bool $federatedShare
* @param bool $isVault
*
* @return ResponseInterface
* @throws GuzzleException
@@ -393,6 +394,7 @@ class SpacesContext implements Context {
string $spaceName,
string $fileName,
bool $federatedShare = false,
bool $isVault = false,
): ResponseInterface {
$baseUrl = $this->featureContext->getBaseUrl();
@@ -400,18 +402,27 @@ class SpacesContext implements Context {
$remoteItemId = $this->getSharesRemoteItemId($user, $spaceName);
$spaceId = \rawurlencode($remoteItemId);
} else {
$space = $this->getSpaceByName($user, $spaceName);
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$spaceId = $space["id"];
}
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $spaceId);
$fullUrl = "$baseUrl/$davPath/$fileName";
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
$headers['Authorization'] = 'Bearer ' . $accessToken;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return HttpRequestHelper::get(
$fullUrl,
$user,
$this->featureContext->getPasswordForUser($user),
[],
$password,
$headers,
"{}",
);
}
@@ -951,11 +962,12 @@ class SpacesContext implements Context {
}
/**
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)" should (not|)\s?contain these (?:files|entries):$/
* @Then /^for user "([^"]*)" folder "([^"]*)" of the space "([^"]*)"(| in vault)? should (not|)\s?contain these (?:files|entries):$/
*
* @param string $user
* @param string $folderPath
* @param string $spaceName
* @param string $isVault
* @param string $shouldOrNot (not|)
* @param TableNode $expectedFiles
*
@@ -967,11 +979,13 @@ class SpacesContext implements Context {
string $user,
string $folderPath,
string $spaceName,
string $isVault,
string $shouldOrNot,
TableNode $expectedFiles,
): void {
$space = $this->getSpaceByName($user, $spaceName);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath));
$isVault = trim($isVault) === 'in vault';
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, $folderPath, $isVault));
$this->featureContext->propfindResultShouldContainEntries(
$shouldOrNot,
$expectedFiles,
@@ -983,11 +997,12 @@ class SpacesContext implements Context {
}
/**
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)" should be "([^"]*)"$/
* @Then /^for user "([^"]*)" the content of the file "([^"]*)" of the space "([^"]*)"(| in vault) should be "([^"]*)"$/
*
* @param string $user
* @param string $file
* @param string $spaceName
* @param string $isVault
* @param string $fileContent
*
* @return void
@@ -998,9 +1013,11 @@ class SpacesContext implements Context {
string $user,
string $file,
string $spaceName,
string $isVault,
string $fileContent,
): void {
$actualFileContent = $this->getFileData($user, $spaceName, $file)->getBody()->getContents();
$isVault = trim($isVault) === 'in vault';
$actualFileContent = $this->getFileData($user, $spaceName, $file, false, $isVault)->getBody()->getContents();
Assert::assertEquals($fileContent, $actualFileContent, "$file does not contain $fileContent");
}
@@ -2080,15 +2097,15 @@ class SpacesContext implements Context {
}
/**
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" using the WebDAV API$/
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)"(?: with following headers) using the WebDAV API$/
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)"(| in vault)? to "([^"]*)" inside space "([^"]*)"(| in vault)? using the WebDAV API$/
*
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $isSourceVault
* @param string $fileDestination
* @param string $toSpaceName
* @param TableNode|null $table
* @param string $isDestinationVault
*
* @return void
* @throws GuzzleException
@@ -2097,15 +2114,86 @@ class SpacesContext implements Context {
string $user,
string $fileSource,
string $fromSpaceName,
string $isSourceVault,
string $fileDestination,
string $toSpaceName,
string $isDestinationVault,
): void {
$isSourceVault = trim($isSourceVault) === "in vault";
$isDestinationVault = trim($isDestinationVault) === "in vault";
$this->copyFileBetweenSpaces(
$user,
$fileSource,
$fromSpaceName,
$fileDestination,
$toSpaceName,
$isSourceVault,
$isDestinationVault,
);
}
/**
* @When /^user "([^"]*)" copies (?:file|folder) "([^"]*)" from space "([^"]*)" to "([^"]*)" inside space "([^"]*)" with following headers using the WebDAV API$/
*
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $fileDestination
* @param string $toSpaceName
* @param TableNode $table
*
* @return void
* @throws GuzzleException
*/
public function userCopiesFileFromAndToSpaceBetweenSpacesWithHeaders(
string $user,
string $fileSource,
string $fromSpaceName,
string $fileDestination,
string $toSpaceName,
TableNode $table,
): void {
$this->copyFileBetweenSpaces(
$user,
$fileSource,
$fromSpaceName,
$fileDestination,
$toSpaceName,
false,
false,
$table,
);
}
/**
* @param string $user
* @param string $fileSource
* @param string $fromSpaceName
* @param string $fileDestination
* @param string $toSpaceName
* @param boolean $isSourceVault
* @param boolean $isDestinationVault
* @param TableNode|null $table
*
* @return void
* @throws GuzzleException
*/
private function copyFileBetweenSpaces(
string $user,
string $fileSource,
string $fromSpaceName,
string $fileDestination,
string $toSpaceName,
?bool $isSourceVault = false,
?bool $isDestinationVault = false,
?TableNode $table = null,
): void {
$space = $this->getSpaceByName($user, $fromSpaceName);
$space = $this->getSpaceByName($user, $fromSpaceName, $isSourceVault);
$headers['Destination'] = $this->destinationHeaderValueWithSpaceName(
$user,
$fileDestination,
$toSpaceName,
$isDestinationVault,
);
if ($table !== null) {
@@ -2281,6 +2369,7 @@ class SpacesContext implements Context {
* @param string $user
* @param string $fileDestination
* @param string $spaceName
* @param boolean $isVault
* @param string|null $endPath
*
* @return string
@@ -2290,9 +2379,10 @@ class SpacesContext implements Context {
string $user,
string $fileDestination,
string $spaceName,
bool $isVault = false,
?string $endPath = null,
): string {
$space = $this->getSpaceByName($user, $spaceName);
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$fileDestination = $this->escapePath(\ltrim($fileDestination, "/"));
$baseUrl = $this->featureContext->getBaseUrl();
$davPath = WebdavHelper::getDavPath(WebDavHelper::DAV_VERSION_SPACES, $space["id"]);
@@ -2310,11 +2400,19 @@ class SpacesContext implements Context {
* @throws GuzzleException
*/
public function copyFilesAndFoldersRequest(string $user, string $fullUrl, array $headers): ResponseInterface {
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
$user = null;
$password = null;
} else {
$password = $this->featureContext->getPasswordForUser($user);
}
return HttpRequestHelper::sendRequest(
$fullUrl,
'COPY',
$user,
$this->featureContext->getPasswordForUser($user),
$password,
$headers,
);
}
@@ -2354,6 +2452,7 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$toSpaceName,
false,
$fileId,
);
}
@@ -2401,6 +2500,7 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2445,6 +2545,7 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2493,6 +2594,7 @@ class SpacesContext implements Context {
$user,
$fileDestination,
$spaceName,
false,
$fileId,
);
}
@@ -2548,12 +2650,13 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"$/
* @Given /^user "([^"]*)" has uploaded a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"(| in vault)?$/
*
* @param string $user
* @param string $spaceName
* @param string $fileContent
* @param string $destination
* @param string $isVault
*
* @return array
* @throws GuzzleException
@@ -2563,8 +2666,10 @@ class SpacesContext implements Context {
string $spaceName,
string $fileContent,
string $destination,
string $isVault,
): array {
$space = $this->getSpaceByName($user, $spaceName);
$isVault = trim($isVault) === "in vault";
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$response = $this->featureContext->uploadFileWithContent(
$user,
$fileContent,
+6 -2
View File
@@ -1,8 +1,12 @@
services:
acceptance-tests:
image: owncloudci/php:8.2
image: owncloudci/php:8.4
working_dir: /ocis
command: /bin/bash /test/run-tests.sh
command: >
/bin/bash -c "command -v composer >/dev/null 2>&1 ||
(php -r \"copy('https://getcomposer.org/installer', '/tmp/composer-setup.php');\" &&
php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer);
/bin/bash /test/run-tests.sh"
environment:
OCIS_ROOT: /ocis
TEST_SERVER_URL: https://ocis-server:9200
@@ -182,3 +182,94 @@ Feature: vault
}
}
"""
Scenario: user copies folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
When user "Alice" copies folder "driveFolder" from space "Personal" to "driveFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| driveFolder |
And for user "Alice" the space "Personal" should contain these entries:
| driveFolder |
Scenario: user copies file from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt"
When user "Alice" copies file "testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" the space "Personal" should contain these entries:
| testfile.txt |
Scenario: user tries to copy folder from vault to drive
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies folder "vaultFolder" from space "Personal" in vault to "vaultFolder" inside space "Personal" using the WebDAV API
Then the HTTP status code should be "409"
And for user "Alice" the space "Personal" should not contain these entries:
| vaultFolder |
And for user "Alice" the space "Personal" in vault should contain these entries:
| vaultFolder |
Scenario: user tries to copy file from vault to drive
Given user "Alice" has logged in via web UI
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "testfile.txt" in vault
When user "Alice" copies file "testfile.txt" from space "Personal" in vault to "testfile.txt" inside space "Personal" using the WebDAV API
Then the HTTP status code should be "409"
And for user "Alice" the space "Personal" should not contain these entries:
| testfile.txt |
And for user "Alice" the space "Personal" in vault should contain these entries:
| testfile.txt |
Scenario: user copies sub-folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "subFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| subFolder |
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| subFolder |
Scenario: user copies file inside folder from drive to vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| testfile.txt |
Scenario: user copies sub-folder from drive to a folder in vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has created a folder "driveFolder/subFolder" in space "Personal"
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies folder "driveFolder/subFolder" from space "Personal" to "vaultFolder/subFolder" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" folder "vaultFolder" of the space "Personal" in vault should contain these entries:
| subFolder |
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| subFolder |
Scenario: user copies file inside folder from drive to a folder in vault
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFolder/testfile.txt"
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" copies file "driveFolder/testfile.txt" from space "Personal" to "vaultFolder/testfile.txt" inside space "Personal" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the content of the file "vaultFolder/testfile.txt" of the space "Personal" in vault should be "some content"
And for user "Alice" folder "driveFolder" of the space "Personal" should contain these entries:
| testfile.txt |
@@ -0,0 +1 @@
lorem
@@ -0,0 +1 @@
lorem
@@ -0,0 +1 @@
lorem
@@ -0,0 +1 @@
lorem
+12
View File
@@ -27,6 +27,18 @@ Use the links above for more information on each.
# changelog
* Jul 1st, 2026 [1.19.0](https://github.com/klauspost/compress/releases/tag/v1.19.0)
* zstd: Add true concurrent stream encodingin https://github.com/klauspost/compress/pull/1136
* zstd: arm64 decoder asm by @lizthegrey in https://github.com/klauspost/compress/pull/1160
* flate: Add inflate checkpoints in https://github.com/klauspost/compress/pull/1154
* zstd: avoid unused BuildDict encoder allocation by @snissn in https://github.com/klauspost/compress/pull/1147
* snappy/s2: Limit length of varint in `decodedLen` by @eustas in https://github.com/klauspost/compress/pull/1148
* gzhttp: match qvalue parameter case-insensitively (RFC 7231) by @z9z in https://github.com/klauspost/compress/pull/1149
* zip: add NameDecoder callback for legacy encoding rewrite by @SAY-5 in https://github.com/klauspost/compress/pull/1150
* huff0: Allow building tables from histogram in https://github.com/klauspost/compress/pull/1155
* huff0: Allow building table from oversized histogram in https://github.com/klauspost/compress/pull/1156
* s2sx: Clean symlink targets in https://github.com/klauspost/compress/pull/1163
* Feb 9th, 2026 [1.18.4](https://github.com/klauspost/compress/releases/tag/v1.18.4)
* gzhttp: Add zstandard to server handler wrapper https://github.com/klauspost/compress/pull/1121
* zstd: Add ResetWithOptions to encoder/decoder https://github.com/klauspost/compress/pull/1122
+21 -3
View File
@@ -28,9 +28,10 @@ type dictDecoder struct {
hist []byte // Sliding window history
// Invariant: 0 <= rdPos <= wrPos <= len(hist)
wrPos int // Current output position in buffer
rdPos int // Have emitted hist[:rdPos] already
full bool // Has a full window length been written yet?
wrPos int // Current output position in buffer
rdPos int // Have emitted hist[:rdPos] already
flushed int64 // Total bytes returned by readFlush since init
full bool // Has a full window length been written yet?
}
// init initializes dictDecoder to have a sliding window dictionary of the given
@@ -167,11 +168,22 @@ loop:
return dstPos - dstBase
}
// appendWindow appends the current sliding window (up to len(hist) most recent
// bytes, oldest first) to dst.
func (dd *dictDecoder) appendWindow(dst []byte) []byte {
if dd.full {
dst = append(dst, dd.hist[dd.wrPos:]...)
return append(dst, dd.hist[:dd.wrPos]...)
}
return append(dst, dd.hist[:dd.wrPos]...)
}
// readFlush returns a slice of the historical buffer that is ready to be
// emitted to the user. The data returned by readFlush must be fully consumed
// before calling any other dictDecoder methods.
func (dd *dictDecoder) readFlush() []byte {
toRead := dd.hist[dd.rdPos:dd.wrPos]
dd.flushed += int64(len(toRead))
dd.rdPos = dd.wrPos
if dd.wrPos == len(dd.hist) {
dd.wrPos, dd.rdPos = 0, 0
@@ -179,3 +191,9 @@ func (dd *dictDecoder) readFlush() []byte {
}
return toRead
}
// decoded reports the total number of bytes written into the dictionary since
// init (i.e. excluding any preset dict bytes).
func (dd *dictDecoder) decoded() int64 {
return dd.flushed + int64(dd.wrPos-dd.rdPos)
}
+92
View File
@@ -342,6 +342,11 @@ type decompressor struct {
final bool
flushMode flushMode
cb func(InflateCheckpoint)
cp InflateCheckpoint
hasCP bool // WithResumeFrom was supplied
uncOffset int64 // baseline uncompressed offset (from a resume checkpoint)
cpBuf []byte
}
func (f *decompressor) nextBlock() {
@@ -676,6 +681,18 @@ func (f *decompressor) finishBlock() {
f.toRead = f.dict.readFlush()
}
if f.cb != nil {
bitPos := f.roffset*8 - int64(f.nb)
f.cpBuf = f.dict.appendWindow(f.cpBuf[:0])
f.cb(InflateCheckpoint{
UncompressedOffset: f.uncOffset + f.dict.decoded(),
CompressedOffset: bitPos / 8,
Final: f.final,
BitOffset: uint8(bitPos & 7),
Window: f.cpBuf,
})
}
f.step = nextBlock
}
@@ -806,6 +823,45 @@ func (f *decompressor) Reset(r io.Reader, dict []byte) error {
return nil
}
// ResetCP will adjust the input to the provided checkpoint.
// It is assumed the input stream is forwarded to cp.CompressedOffset.
func (f *decompressor) ResetCP(r io.Reader, cp InflateCheckpoint) error {
*f = decompressor{
r: makeReader(r),
bits: f.bits,
codebits: f.codebits,
h1: f.h1,
h2: f.h2,
dict: f.dict,
step: nextBlock,
cpBuf: f.cpBuf,
}
return f.applyCP(cp)
}
// applyCP seeds the decompressor state from a resume checkpoint:
// loads the sliding window, sets the absolute compressed/uncompressed
// offsets, and skips cp.BitOffset bits into the first input byte so
// the next decode aligns with the start of a deflate block.
func (f *decompressor) applyCP(cp InflateCheckpoint) error {
f.dict.init(maxMatchOffset, cp.Window)
f.roffset = cp.CompressedOffset
f.uncOffset = cp.UncompressedOffset
f.final = cp.Final
f.b = 0
f.nb = 0
if cp.BitOffset > 0 {
c, err := f.r.ReadByte()
if err != nil {
return noEOF(err)
}
f.roffset++
f.b = uint32(c) >> cp.BitOffset
f.nb = 8 - uint(cp.BitOffset)
}
return nil
}
type ReaderOpt func(*decompressor)
// WithPartialBlock tells decompressor to return after each block,
@@ -823,6 +879,36 @@ func WithDict(dict []byte) ReaderOpt {
}
}
// InflateCheckpoint provides a resumable checkpoint for inflate.
type InflateCheckpoint struct {
UncompressedOffset int64 // Byte offset in the decompressed stream
CompressedOffset int64 // Byte offset in the compressed stream
Final bool // True if this is the final block
BitOffset uint8 // 0-7 bits
Window []byte // 32KB sliding window dictionary
}
// WithEobCallback will call the provided function after each block
// with the current gzip checkpoint.
// After returning the provided window can no longer be referenced.
// The callback will not be triggered after a block is marked "final".
// The callback is not retained after Reset.
func WithEobCallback(cb func(InflateCheckpoint)) ReaderOpt {
return func(f *decompressor) {
f.cb = cb
}
}
// WithResumeFrom will adjust the input to the provided checkpoint.
// It is assumed the input stream is forwarded to the provided offset.
// The checkpoint is removed when Reset is called.
func WithResumeFrom(cp InflateCheckpoint) ReaderOpt {
return func(f *decompressor) {
f.cp = cp
f.hasCP = true
}
}
// NewReaderOpts returns new reader with provided options
func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
fixedHuffmanDecoderInit()
@@ -838,6 +924,12 @@ func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
opt(&f)
}
if f.hasCP {
if err := f.applyCP(f.cp); err != nil {
f.err = err
}
}
return &f
}
+85 -31
View File
@@ -10,6 +10,15 @@ import (
"strings"
)
func peekBufio(fr *bufio.Reader) ([]byte, error) {
if fr.Buffered() == 0 {
if _, err := fr.Peek(1); err != nil && fr.Buffered() == 0 {
return nil, err
}
}
return fr.Peek(fr.Buffered())
}
// Decode a single Huffman block from f.
// hl and hd are the Huffman states for the lit/length values
// and the distance values, respectively. If hd == nil, using the
@@ -527,6 +536,8 @@ func (f *decompressor) huffmanBufioReader() {
// but is smart enough to keep local variables in registers, so use nb and b,
// inline call to moreBits and reassign b,nb back to f on return.
fnb, fb, dict := f.nb, f.b, &f.dict
pbuf, _ := fr.Peek(fr.Buffered())
pos := 0
switch f.stepState {
case stateInit:
@@ -548,12 +559,19 @@ readLiteral:
n := uint(f.hl.maxRead)
for {
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
}
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -566,6 +584,7 @@ readLiteral:
}
if n <= fnb {
if n == 0 {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("huffsym: n==0")
@@ -586,6 +605,7 @@ readLiteral:
case v < 256:
dict.writeByte(byte(v))
if dict.availWrite() == 0 {
fr.Discard(pos)
f.toRead = dict.readFlush()
f.step = huffmanBufioReader
f.stepState = stateInit
@@ -594,6 +614,7 @@ readLiteral:
}
goto readLiteral
case v == 256:
fr.Discard(pos)
f.b, f.nb = fb, fnb
f.finishBlock()
return
@@ -605,15 +626,22 @@ readLiteral:
length = int(val.length) + 3
n := uint(val.extra)
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits n>0:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -622,6 +650,7 @@ readLiteral:
fb >>= n & regSizeMaskUint32
fnb -= n
default:
fr.Discard(pos)
if debugDecode {
fmt.Println(v, ">= maxNumLit")
}
@@ -633,15 +662,22 @@ readLiteral:
var dist uint32
if f.hd == nil {
for fnb < 5 {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -660,12 +696,19 @@ readLiteral:
// inline call to moreBits and reassign b,nb back to f on return.
for {
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
}
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -678,6 +721,7 @@ readLiteral:
}
if n <= fnb {
if n == 0 {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("huffsym: n==0")
@@ -701,15 +745,22 @@ readLiteral:
// have 1 bit in bottom of dist, need nb more.
extra := (dist & 1) << (nb & regSizeMaskUint32)
for fnb < nb {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -720,6 +771,7 @@ readLiteral:
dist = 1<<((nb+1)&regSizeMaskUint32) + 1 + extra
// slower: dist = bitMask32[nb+1] + 2 + extra
default:
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("dist too big:", dist, maxNumDist)
@@ -730,6 +782,7 @@ readLiteral:
// No check on length; encoding can be prescient.
if dist > uint32(dict.histSize()) {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("dist > dict.histSize():", dist, dict.histSize())
@@ -752,6 +805,7 @@ copyHistory:
f.copyLen -= cnt
if dict.availWrite() == 0 || f.copyLen > 0 {
fr.Discard(pos)
f.toRead = dict.readFlush()
f.step = huffmanBufioReader // We need to continue this work
f.stepState = stateDict
+168
View File
@@ -0,0 +1,168 @@
package huff0
import "errors"
// BuildCTable builds a Huffman compression table from a precomputed symbol
// histogram and installs it as the previous (reuse) table on s.
//
// After this call:
// - EstimateSize/CanUseTable can probe the table against other histograms.
// - Compress1X/Compress4X with Reuse = ReusePolicyMust will encode without
// emitting a new table header.
// - TransferCTable can hand the table to a sibling Scratch.
//
// count[i] is the number of occurrences of symbol i. The histogram must have
// at least 2 distinct non-zero symbols; ErrUseRLE is returned for a single
// symbol and an error is returned for an empty histogram.
func (s *Scratch) BuildCTable(count *[256]uint32) error {
if s == nil {
return errors.New("huff0: BuildCTable on nil Scratch")
}
if count == nil {
return errors.New("huff0: nil count passed to BuildCTable")
}
var err error
s, err = s.prepare(nil)
if err != nil {
return err
}
s.count = *count
var total, maxCount int
var symLen uint16
for i, v := range s.count {
total += int(v)
if int(v) > maxCount {
maxCount = int(v)
}
if v != 0 {
symLen = uint16(i) + 1
}
}
if total == 0 {
return errors.New("huff0: empty histogram")
}
if symLen < 2 || maxCount == total {
return ErrUseRLE
}
// huff0's internal rank table assumes total ≤ BlockSizeMax (it uses
// highBit32(count+1) + 1 as a rank index into a fixed-size array).
// Histograms summed across multiple blocks can exceed that; scale the
// counts down preserving the distribution. Non-zero entries round up so
// rare symbols stay representable.
if total > BlockSizeMax {
shift := uint(0)
for total>>shift > BlockSizeMax {
shift++
}
round := uint32(1<<shift) - 1
var newTotal, newMax int
for i, v := range s.count {
if v == 0 {
continue
}
scaled := (v + round) >> shift
if scaled == 0 {
scaled = 1
}
s.count[i] = scaled
newTotal += int(scaled)
if int(scaled) > newMax {
newMax = int(scaled)
}
}
total = newTotal
maxCount = newMax
if maxCount == total {
return ErrUseRLE
}
}
s.symbolLen = symLen
s.maxCount = maxCount
s.srcLen = total
if err := s.buildCTable(); err != nil {
return err
}
if cap(s.prevTable) < len(s.cTable) {
s.prevTable = make(cTable, 0, maxSymbolValue+1)
}
s.prevTable = s.prevTable[:len(s.cTable)]
copy(s.prevTable, s.cTable)
s.prevTableLog = s.actualTableLog
// Force the next Compress* to recount from real input.
s.clearCount = true
s.maxCount = 0
return nil
}
// EstimateSize returns an estimated compressed payload size in bytes for the
// supplied histogram using the table currently stored in prevTable. It returns
// -1 when the table cannot encode every non-zero symbol of hist (i.e. when
// CanUseTable would return false). The estimate excludes the table header.
func (s *Scratch) EstimateSize(hist *[256]uint32) int {
if s == nil || hist == nil || len(s.prevTable) == 0 {
return -1
}
pt := s.prevTable
nbBits := uint32(7)
for i, v := range hist {
if v == 0 {
continue
}
if i >= len(pt) || pt[i].nBits == 0 {
return -1
}
nbBits += uint32(pt[i].nBits) * v
}
return int(nbBits >> 3)
}
// CanUseTable reports whether the table in prevTable can encode every
// non-zero symbol present in hist.
func (s *Scratch) CanUseTable(hist *[256]uint32) bool {
if s == nil || hist == nil || len(s.prevTable) == 0 {
return false
}
pt := s.prevTable
for i, v := range hist {
if v == 0 {
continue
}
if i >= len(pt) || pt[i].nBits == 0 {
return false
}
}
return true
}
// AppendTable serializes the table currently stored in prevTable (e.g. as
// installed by BuildCTable or carried over from a previous Compress call)
// into a self-delimiting zstd-style header and appends it to dst. The
// returned slice can be parsed back by ReadTable.
func (s *Scratch) AppendTable(dst []byte) ([]byte, error) {
if s == nil || len(s.prevTable) == 0 {
return dst, errors.New("huff0: AppendTable with empty table")
}
// cTable.write reads s.actualTableLog, s.symbolLen, s.huffWeight, s.fse
// and writes into s.Out. Save/restore Out so we don't disturb in-flight
// compression buffers.
saveOut := s.Out
saveTL := s.actualTableLog
saveSL := s.symbolLen
if s.fse == nil {
// Lazily init in case AppendTable is called on a fresh Scratch.
if _, err := s.prepare(nil); err != nil {
return dst, err
}
saveOut = s.Out
}
s.Out = s.Out[:0]
s.actualTableLog = s.prevTableLog
s.symbolLen = uint16(len(s.prevTable))
if err := s.prevTable.write(s); err != nil {
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
return dst, err
}
dst = append(dst, s.Out...)
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
return dst, nil
}
+1 -1
View File
@@ -31,7 +31,7 @@ func DecodedLen(src []byte) (int, error) {
// that the length header occupied.
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
v, n := binary.Uvarint(src)
if n <= 0 || v > 0xffffffff {
if n <= 0 || n > 5 || v > 0xffffffff {
return 0, 0, ErrCorrupt
}
+1 -1
View File
@@ -35,7 +35,7 @@ func DecodedLen(src []byte) (int, error) {
// that the length header occupied.
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
v, n := binary.Uvarint(src)
if n <= 0 || v > 0xffffffff {
if n <= 0 || n > 5 || v > 0xffffffff {
return 0, 0, ErrCorrupt
}
+4 -2
View File
@@ -56,10 +56,12 @@ func NewDict(dict []byte) *Dict {
if len(dict) < MinDictSize || len(dict) > MaxDictSize {
return nil
}
d.repeat = int(r)
if d.repeat > len(dict) {
// Compare as uint64: int(r) would wrap negative for r > MaxInt64,
// slipping past the bounds check and causing an OOB read in encode.
if r > uint64(len(dict)) {
return nil
}
d.repeat = int(r)
return &d
}
+1 -1
View File
@@ -981,7 +981,7 @@ searchDict:
cv = load64(src, s)
continue
}
} else if uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
} else if repeat > 0 && uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
base := s + checkRep
// Extend back
for i := base - repeat; base > nextEmit && i > 0 && src[i-1] == src[base-1]; {
+3 -3
View File
@@ -25,7 +25,7 @@ type betterTables struct {
sTable [betterShortTableSize]uint32
}
var betterTablePool = sync.Pool{New: func() interface{} { return &betterTables{} }}
var betterTablePool = sync.Pool{New: func() any { return &betterTables{} }}
// betterSnappyTables holds better-snappy compression hash tables.
type betterSnappyTables struct {
@@ -33,7 +33,7 @@ type betterSnappyTables struct {
sTable [betterShortTableSize]uint32
}
var betterSnappyTablePool = sync.Pool{New: func() interface{} { return &betterSnappyTables{} }}
var betterSnappyTablePool = sync.Pool{New: func() any { return &betterSnappyTables{} }}
// bestTables holds best compression hash tables.
type bestTables struct {
@@ -41,7 +41,7 @@ type bestTables struct {
sTable [bestShortTableSize]uint64
}
var bestTablePool = sync.Pool{New: func() interface{} { return &bestTables{} }}
var bestTablePool = sync.Pool{New: func() any { return &bestTables{} }}
// getBetterTables gets a zeroed betterTables from the pool.
func getBetterTables() *betterTables {
+12 -7
View File
@@ -216,13 +216,18 @@ func (r *Reader) skippable(tmp []byte, n int, allowEOF bool, id uint8) (ok bool)
return r.err == nil
}
if rs, ok := r.r.(io.ReadSeeker); ok {
_, err := rs.Seek(int64(n), io.SeekCurrent)
if err == nil {
return true
}
if err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
r.err = ErrCorrupt
return false
if cur, err := rs.Seek(0, io.SeekCurrent); err == nil {
if end, err := rs.Seek(0, io.SeekEnd); err == nil {
if cur+int64(n) <= end {
if _, err := rs.Seek(cur+int64(n), io.SeekStart); err == nil {
return true
}
}
if _, err := rs.Seek(cur, io.SeekStart); err != nil {
r.err = ErrCorrupt
return false
}
}
}
}
for n > 0 {
+130
View File
@@ -0,0 +1,130 @@
// Copyright 2011 The Snappy-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package snappy
import "encoding/binary"
// DecodeStrict returns the decoded form of src, like Decode.
//
// Unlike Decode, which delegates to the s2 decoder and accepts the s2
// "repeat last offset" extension (a copy whose encoded offset is 0),
// DecodeStrict uses a strict standard-Snappy block decoder. Offset 0 is not
// valid in the standard Snappy block format, so such a copy is rejected with
// ErrCorrupt. This makes DecodeStrict match github.com/golang/snappy and the
// C++ reference decoder, at the cost of being slower than Decode.
//
// The returned slice may be a sub-slice of dst if dst was large enough to
// hold the entire decoded block. Otherwise, a newly allocated slice will be
// returned.
//
// The dst and src must not overlap. It is valid to pass a nil dst.
//
// DecodeStrict handles the Snappy block format, not the Snappy stream format.
func DecodeStrict(dst, src []byte) ([]byte, error) {
v, n := binary.Uvarint(src)
if n <= 0 || n > 5 || v > 0xffffffff {
return nil, ErrCorrupt
}
const wordSize = 32 << (^uint(0) >> 32 & 1)
if wordSize == 32 && v > 0x7fffffff {
return nil, ErrTooLarge
}
dLen := int(v)
if dLen <= cap(dst) {
dst = dst[:dLen]
} else {
dst = make([]byte, dLen)
}
if decodeStrict(dst, src[n:]) != 0 {
return nil, ErrCorrupt
}
return dst, nil
}
func decodeStrict(dst, src []byte) int {
var d, s, offset, length int
for s < len(src) {
switch src[s] & 0x03 {
case 0x00:
x := uint32(src[s] >> 2)
switch {
case x < 60:
s++
case x == 60:
s += 2
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-1])
case x == 61:
s += 3
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-2]) | uint32(src[s-1])<<8
case x == 62:
s += 4
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
case x == 63:
s += 5
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
}
length = int(x) + 1
if length <= 0 || length > len(dst)-d || length > len(src)-s {
return 1
}
copy(dst[d:], src[s:s+length])
d += length
s += length
continue
case 0x01:
s += 2
if uint(s) > uint(len(src)) {
return 1
}
length = 4 + int(src[s-2])>>2&0x7
offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
case 0x02:
s += 3
if uint(s) > uint(len(src)) {
return 1
}
length = 1 + int(src[s-3])>>2
offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
case 0x03:
s += 5
if uint(s) > uint(len(src)) {
return 1
}
length = 1 + int(src[s-5])>>2
offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
}
if offset <= 0 || d < offset || length > len(dst)-d {
return 1
}
if offset >= length {
copy(dst[d:d+length], dst[d-offset:])
d += length
continue
}
a := dst[d : d+length]
b := dst[d-offset:]
b = b[:len(a)]
for i := range a {
a[i] = b[i]
}
d += length
}
if d != len(dst) {
return 1
}
return 0
}
+35 -2
View File
@@ -75,14 +75,47 @@ The above is fine for big encodes. However, whenever possible try to *reuse* the
To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output.
This will allow the encoder to reuse all resources and avoid wasteful allocations.
Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
By default, stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
in the future. So if you want to limit concurrency for future updates, specify the concurrency
you would like.
If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)`
which will compress input as each block is completed, blocking on writes until each has completed.
#### Parallel Stream Compression
For maximum throughput on large streams, use `WithConcurrentBlocks(true)` together with
`WithEncoderConcurrency(n)` where n is the number of CPU cores you want to use.
This splits the input into large sections (jobs) that are compressed simultaneously by multiple goroutines,
similar to how the C zstd library does multithreaded compression.
```Go
enc, err := zstd.NewWriter(out,
zstd.WithEncoderLevel(zstd.SpeedDefault),
zstd.WithEncoderConcurrency(runtime.GOMAXPROCS(0)),
zstd.WithConcurrentBlocks(true),
)
```
Each non-first job receives an overlap prefix from the previous job for match context,
so compression ratio is only marginally affected. Output is flushed in order,
producing a valid single-frame zstd stream.
Benchmark on 1.8GB GOB stream (AMD Ryzen 9 9950X):
| Level | 1 thread | 4 threads | 16 threads | 1T ratio | 16T ratio |
|---------|:----------:|:------------------:|:-------------------:|:--------:|:---------:|
| fastest | 783 MB/s | 2950 MB/s (3.8×) | 6939 MB/s (8.9×) | 12.24% | 12.26% |
| default | 728 MB/s | 2533 MB/s (3.5×) | 5340 MB/s (7.3×) | 10.67% | 10.68% |
| better | 434 MB/s | 1105 MB/s (2.5×) | 2206 MB/s (5.1×) | 9.14% | 9.21% |
| best | 129 MB/s | 367 MB/s (2.8×) | 884 MB/s (6.8×) | 8.48% | 8.63% |
Notes:
* Not compatible with dictionary encoding.
* `Flush()` dispatches the current partial job, so latency-sensitive callers can force output.
* `EncodeAll` is unaffected — it uses its own concurrency via the encoder pool.
You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined
compression settings can be specified.
+2 -1
View File
@@ -230,7 +230,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
}
block := blockEnc{lowMem: false}
block.init()
enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
var enc encoder
if o.Level != 0 {
eOpts := encoderOptions{
level: o.Level,
@@ -242,6 +242,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
enc = eOpts.encoder()
} else {
o.Level = SpeedBestCompression
enc = encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
}
var (
remain [256]int
+28
View File
@@ -128,6 +128,34 @@ func (e *fastBase) matchlen(s, t int32, src []byte) int32 {
return int32(matchLen(src[s:], src[t:]))
}
// resetBasePrefix resets the encoder state and loads prefix as initial history.
// This is used for parallel job encoding where non-first jobs need overlap context.
// Rep offsets are set to defaults [1,4,8] (invalidated, matching C behavior).
func (e *fastBase) resetBasePrefix(prefix []byte) {
if e.blk == nil {
e.blk = &blockEnc{lowMem: e.lowMem}
e.blk.init()
} else {
e.blk.reset(nil)
}
e.blk.initNewEncode()
if e.crc == nil {
e.crc = xxhash.New()
} else {
e.crc.Reset()
}
e.blk.dictLitEnc = nil
e.ensureHist(len(prefix) + maxCompressedBlockSize)
// Bump cur so old table entries fall outside the window.
// When cur >= bufferReset, leave it; the first Encode call
// will shift/clear tables, preserving valid prefix entries.
if e.cur < e.bufferReset {
e.cur += e.maxMatchOff + int32(len(e.hist))
}
e.hist = e.hist[:0]
e.hist = append(e.hist, prefix...)
}
// Reset the encoding table.
func (e *fastBase) resetBase(d *dict, singleBlock bool) {
if e.blk == nil {
+15
View File
@@ -551,3 +551,18 @@ func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) {
// Reset table to initial state
copy(e.table[:], e.dictTable)
}
func (e *bestFastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur; i < end; i++ {
cv := load6432(prefix, i-e.cur)
h := hashLen(cv, bestLongTableBits, bestLongLen)
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
h0 := hashLen(cv, bestShortTableBits, bestShortLen)
e.table[h0] = prevEntry{offset: i, prev: e.table[h0].offset}
}
}
+18
View File
@@ -1096,6 +1096,20 @@ func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *betterFastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur; i < end; i += 2 {
cv := load6432(prefix, i-e.cur)
h := hashLen(cv, betterLongTableBits, betterLongLen)
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
e.table[hashLen(cv>>8, betterShortTableBits, betterShortLen)] = tableEntry{val: uint32(cv >> 8), offset: i + 1}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
e.resetBase(d, singleBlock)
@@ -1229,6 +1243,10 @@ func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
e.allDirty = false
}
func (e *betterFastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) {
e.longTableShardDirty[entryNum/betterLongTableShardSize] = true
}
+16
View File
@@ -1037,6 +1037,18 @@ func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *doubleFastEncoder) ResetPrefix(prefix []byte) {
e.fastEncoder.ResetPrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur + 1; i < end; i += 2 {
cv := load6432(prefix, i-e.cur)
e.longTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{val: uint32(cv), offset: i}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
allDirty := e.allDirty
@@ -1102,6 +1114,10 @@ func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
}
}
func (e *doubleFastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) {
e.longTableShardDirty[entryNum/dLongTableShardSize] = true
}
+17
View File
@@ -797,6 +797,19 @@ func (e *fastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *fastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
// Index every 4th
for i := e.cur + 1; i < end; i += 4 {
cv := load6432(prefix, i-e.cur)
e.table[hashLen(cv, tableBits, tableFastHashLen)] = tableEntry{val: uint32(cv), offset: i}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
e.resetBase(d, singleBlock)
@@ -866,6 +879,10 @@ func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
e.allDirty = false
}
func (e *fastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *fastEncoderDict) markAllShardsDirty() {
e.allDirty = true
}
+352
View File
@@ -0,0 +1,352 @@
// Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"fmt"
rdebug "runtime/debug"
"sync"
)
type encJob struct {
prefix []byte // overlap from previous job (nil for first)
input []byte // job's own input data (swapped from filling)
last bool // last block of last job gets last=true
output []byte // compressed blocks (filled by worker)
err error // encoding error
done chan struct{} // closed when complete
}
type jobState struct {
jobSize int
overlapSize int
filling []byte // accumulates input up to jobSize
nextPrefix []byte // overlap prefix prepared for the next dispatched job
jobSeq int // next job sequence number
jobCh chan *encJob // dispatch to workers
resultCh chan *encJob // ordered results to flusher
workerWg sync.WaitGroup
flusherWg sync.WaitGroup
mu sync.Mutex
flushedSeq int // last flushed sequence number
cond *sync.Cond
flusherErr error
started bool
inputPool sync.Pool // *[]byte buffers of jobSize cap
outputPool sync.Pool // *[]byte buffers for compressed output
overlapPool sync.Pool // *[]byte buffers for overlap prefixes
}
func (e *Encoder) startJobWorkers() {
js := &e.state.jobs
n := e.o.concurrent
js.jobCh = make(chan *encJob, n)
js.resultCh = make(chan *encJob, n)
js.flushedSeq = 0
js.cond = sync.NewCond(&js.mu)
// Workers borrow encoders from the shared e.encoders pool per-job.
// Ensure the pool is initialized before any worker tries to borrow.
e.init.Do(e.initialize)
for range n {
js.workerWg.Add(1)
go e.jobWorker()
}
js.flusherWg.Add(1)
go e.jobFlusher()
js.started = true
}
func (e *Encoder) jobWorker() {
js := &e.state.jobs
defer js.workerWg.Done()
for job := range js.jobCh {
enc := <-e.encoders
e.compressJob(enc, job)
e.encoders <- enc
close(job.done)
}
}
func (e *Encoder) compressJob(enc encoder, job *encJob) {
defer func() {
if r := recover(); r != nil {
job.err = fmt.Errorf("panic in parallel job: %v", r)
rdebug.PrintStack()
}
}()
if len(job.prefix) > 0 {
enc.ResetPrefix(job.prefix)
} else {
enc.Reset(nil, false)
}
data := job.input
if len(data) == 0 && job.last {
blk := enc.Block()
blk.reset(nil)
blk.last = true
blk.encodeRaw(nil)
job.output = append(job.output, blk.output...)
return
}
blk := enc.Block()
for len(data) > 0 {
todo := data
if len(todo) > e.o.blockSize {
todo = todo[:e.o.blockSize]
}
data = data[len(todo):]
blk.pushOffsets()
enc.Encode(blk, todo)
blk.last = len(data) == 0 && job.last
err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy)
if err != nil {
job.err = err
return
}
job.output = append(job.output, blk.output...)
blk.reset(nil)
}
}
func (js *jobState) getInputBuf(size int) []byte {
if v := js.inputPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:0]
}
}
return make([]byte, 0, size)
}
func (js *jobState) putInputBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.inputPool.Put(&b)
}
}
func (js *jobState) getOutputBuf(size int) []byte {
if v := js.outputPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:0]
}
}
return make([]byte, 0, size)
}
func (js *jobState) putOutputBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.outputPool.Put(&b)
}
}
func (js *jobState) getOverlapBuf(size int) []byte {
if v := js.overlapPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:size]
}
}
return make([]byte, size)
}
func (js *jobState) putOverlapBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.overlapPool.Put(&b)
}
}
func (e *Encoder) jobFlusher() {
js := &e.state.jobs
defer js.flusherWg.Done()
for job := range js.resultCh {
<-job.done
// Worker has fully exited compressJob, so the prefix is no longer
// in use. Return it to the pool regardless of outcome.
if job.prefix != nil {
js.putOverlapBuf(job.prefix)
job.prefix = nil
}
if job.err != nil {
js.mu.Lock()
js.flusherErr = job.err
js.cond.Broadcast()
js.mu.Unlock()
for range js.resultCh {
}
return
}
if len(job.output) > 0 {
_, err := e.state.w.Write(job.output)
if err != nil {
js.mu.Lock()
js.flusherErr = err
js.cond.Broadcast()
js.mu.Unlock()
for range js.resultCh {
}
return
}
e.state.nWritten += int64(len(job.output))
}
// Return buffers to pools.
js.putInputBuf(job.input)
js.putOutputBuf(job.output)
job.input = nil
job.output = nil
js.mu.Lock()
js.flushedSeq++
js.cond.Broadcast()
js.mu.Unlock()
}
}
func (e *Encoder) shutdownJobWorkers() {
js := &e.state.jobs
if !js.started {
return
}
close(js.jobCh)
js.workerWg.Wait()
close(js.resultCh)
js.flusherWg.Wait()
js.started = false
}
// waitAllJobs blocks until all dispatched jobs have been flushed.
func (e *Encoder) waitAllJobs() {
js := &e.state.jobs
if !js.started {
return
}
js.mu.Lock()
for js.flushedSeq < js.jobSeq && js.flusherErr == nil {
js.cond.Wait()
}
js.mu.Unlock()
}
func (e *Encoder) dispatchJob(final bool) error {
s := &e.state
js := &s.jobs
js.mu.Lock()
fErr := js.flusherErr
js.mu.Unlock()
if fErr != nil {
return fErr
}
if !s.headerWritten {
// Single-block optimization: fall through to encodeAll path.
if final && len(js.filling) > 0 && len(js.filling) <= e.o.blockSize {
s.current = e.encodeAll(s.encoder, js.filling, s.current[:0])
var n2 int
n2, s.err = s.w.Write(s.current)
if s.err != nil {
return s.err
}
s.nWritten += int64(n2)
s.nInput += int64(len(js.filling))
s.current = s.current[:0]
js.filling = js.filling[:0]
s.headerWritten = true
s.fullFrameWritten = true
s.eofWritten = true
return nil
}
if final && len(js.filling) == 0 && !e.o.fullZero {
s.headerWritten = true
s.fullFrameWritten = true
s.eofWritten = true
return nil
}
var tmp [maxHeaderSize]byte
fh := frameHeader{
ContentSize: uint64(s.frameContentSize),
WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)),
SingleSegment: false,
Checksum: e.o.crc,
DictID: 0,
}
dst := fh.appendTo(tmp[:0])
var n2 int
n2, s.err = s.w.Write(dst)
if s.err != nil {
return s.err
}
s.nWritten += int64(n2)
s.headerWritten = true
}
if len(js.filling) == 0 && !final {
return nil
}
if !js.started {
e.startJobWorkers()
}
// Estimate output size for pooled buffer.
outputEst := max(len(js.filling)/2, 512)
job := &encJob{
last: final,
done: make(chan struct{}),
output: js.getOutputBuf(outputEst),
}
// Each job owns its prefix slice; the flusher returns it to the pool
// after <-job.done, so workers and dispatch never share a buffer.
if js.nextPrefix != nil {
job.prefix = js.nextPrefix
js.nextPrefix = nil
}
// Build the next job's prefix from the tail of this job's input.
if !final && len(js.filling) > 0 {
overlapLen := min(js.overlapSize, len(js.filling))
np := js.getOverlapBuf(overlapLen)
copy(np, js.filling[len(js.filling)-overlapLen:])
js.nextPrefix = np
}
// Swap filling buffer into job — zero-copy for the input data.
job.input = js.filling
js.filling = js.getInputBuf(js.jobSize)
s.nInput += int64(len(job.input))
js.jobSeq++
if final {
s.eofWritten = true
}
js.resultCh <- job
js.jobCh <- job
return nil
}
+206 -4
View File
@@ -38,6 +38,7 @@ type encoder interface {
WindowSize(size int64) int32
UseBlock(*blockEnc)
Reset(d *dict, singleBlock bool)
ResetPrefix(prefix []byte)
}
type encoderState struct {
@@ -60,6 +61,9 @@ type encoderState struct {
wg sync.WaitGroup
// This waitgroup indicates we have a block encoding/writing.
wWg sync.WaitGroup
// Parallel job state (used when concurrentBlocks is enabled).
jobs jobState
}
// NewWriter will create a new Zstandard encoder.
@@ -74,6 +78,9 @@ func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) {
return nil, err
}
}
if e.o.concurrentBlocks && (e.o.dict != nil || e.o.concurrent <= 1) {
e.o.concurrentBlocks = false
}
if w != nil {
e.Reset(w)
}
@@ -95,12 +102,31 @@ func (e *Encoder) initialize() {
// as a new, independent stream.
func (e *Encoder) Reset(w io.Writer) {
s := &e.state
if e.o.concurrentBlocks {
e.shutdownJobWorkers()
js := &s.jobs
js.jobSize = e.o.jobSize()
js.overlapSize = e.o.overlapSize()
// js.filling is allocated lazily on first Write/ReadFrom so callers
// that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost.
js.filling = js.filling[:0]
if js.nextPrefix != nil {
js.putOverlapBuf(js.nextPrefix)
js.nextPrefix = nil
}
js.jobSeq = 0
js.flushedSeq = 0
js.flusherErr = nil
js.started = false
}
s.wg.Wait()
s.wWg.Wait()
if cap(s.filling) == 0 {
s.filling = make([]byte, 0, e.o.blockSize)
}
if e.o.concurrent > 1 {
if e.o.concurrent > 1 && !e.o.concurrentBlocks {
if cap(s.current) == 0 {
s.current = make([]byte, 0, e.o.blockSize)
}
@@ -145,6 +171,9 @@ func (e *Encoder) ResetWithOptions(w io.Writer, opts ...EOption) error {
}
}
hasDict := e.o.dict != nil
if e.o.concurrentBlocks && hasDict {
e.o.concurrentBlocks = false
}
if hadDict != hasDict {
// Dict presence changed — encoder type must be recreated.
e.state.encoder = nil
@@ -176,6 +205,49 @@ func (e *Encoder) Write(p []byte) (n int, err error) {
if s.eofWritten {
return 0, ErrEncoderClosed
}
if e.o.concurrentBlocks {
return e.writeJobs(p)
}
return e.writeBlocks(p)
}
func (e *Encoder) writeJobs(p []byte) (n int, err error) {
s := &e.state
js := &s.jobs
jobSize := js.jobSize
if cap(js.filling) == 0 && len(p) > 0 {
js.filling = make([]byte, 0, jobSize)
}
for len(p) > 0 {
if len(p)+len(js.filling) < jobSize {
if e.o.crc {
_, _ = s.encoder.CRC().Write(p)
}
js.filling = append(js.filling, p...)
return n + len(p), nil
}
add := p
if len(p)+len(js.filling) > jobSize {
add = add[:jobSize-len(js.filling)]
}
if e.o.crc {
_, _ = s.encoder.CRC().Write(add)
}
js.filling = append(js.filling, add...)
p = p[len(add):]
n += len(add)
if len(js.filling) < jobSize {
return n, nil
}
if err := e.dispatchJob(false); err != nil {
return n, err
}
}
return n, nil
}
func (e *Encoder) writeBlocks(p []byte) (n int, err error) {
s := &e.state
for len(p) > 0 {
if len(p)+len(s.filling) < e.o.blockSize {
if e.o.crc {
@@ -374,6 +446,10 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
println("Using ReadFrom")
}
if e.o.concurrentBlocks {
return e.readFromJobs(r)
}
// Flush any current writes.
if len(e.state.filling) > 0 {
if err := e.nextBlock(false); err != nil {
@@ -387,7 +463,6 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
if e.o.crc {
_, _ = e.state.encoder.CRC().Write(src[:n2])
}
// src is now the unfilled part...
src = src[n2:]
n += int64(n2)
switch err {
@@ -420,15 +495,63 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
}
}
func (e *Encoder) readFromJobs(r io.Reader) (n int64, err error) {
js := &e.state.jobs
jobSize := js.jobSize
// Flush any current filling.
if len(js.filling) > 0 {
if err := e.dispatchJob(false); err != nil {
return 0, err
}
}
if cap(js.filling) < jobSize {
js.filling = make([]byte, 0, jobSize)
}
js.filling = js.filling[:jobSize]
src := js.filling
for {
n2, err := r.Read(src)
if e.o.crc {
_, _ = e.state.encoder.CRC().Write(src[:n2])
}
src = src[n2:]
n += int64(n2)
switch err {
case io.EOF:
js.filling = js.filling[:len(js.filling)-len(src)]
return n, nil
case nil:
default:
e.state.err = err
return n, err
}
if len(src) > 0 {
continue
}
if err = e.dispatchJob(false); err != nil {
return n, err
}
if cap(js.filling) < jobSize {
js.filling = make([]byte, 0, jobSize)
}
js.filling = js.filling[:jobSize]
src = js.filling
}
}
// Flush will send the currently written data to output
// and block until everything has been written.
// This should only be used on rare occasions where pushing the currently queued data is critical.
func (e *Encoder) Flush() error {
s := &e.state
if e.o.concurrentBlocks {
return e.flushJobs()
}
if len(s.filling) > 0 {
err := e.nextBlock(false)
if err != nil {
// Ignore Flush after Close.
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
@@ -438,7 +561,6 @@ func (e *Encoder) Flush() error {
s.wg.Wait()
s.wWg.Wait()
if s.err != nil {
// Ignore Flush after Close.
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
@@ -447,6 +569,20 @@ func (e *Encoder) Flush() error {
return s.writeErr
}
func (e *Encoder) flushJobs() error {
js := &e.state.jobs
if len(js.filling) > 0 {
if err := e.dispatchJob(false); err != nil {
return err
}
}
e.waitAllJobs()
js.mu.Lock()
fErr := js.flusherErr
js.mu.Unlock()
return fErr
}
// Close will flush the final output and close the stream.
// The function will block until everything has been written.
// The Encoder can still be re-used after calling this.
@@ -455,12 +591,16 @@ func (e *Encoder) Close() error {
if s.encoder == nil {
return nil
}
if e.o.concurrentBlocks {
return e.closeJobs()
}
if s.w == nil {
if len(s.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
return nil
}
return errors.New("zstd: encoder has no writer")
}
err := e.nextBlock(true)
if err != nil {
if errors.Is(s.err, ErrEncoderClosed) {
@@ -511,6 +651,68 @@ func (e *Encoder) Close() error {
return s.err
}
func (e *Encoder) closeJobs() error {
s := &e.state
js := &s.jobs
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
if s.w == nil {
if len(js.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
return nil
}
return errors.New("zstd: encoder has no writer")
}
if err := e.dispatchJob(true); err != nil {
e.shutdownJobWorkers()
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
return err
}
if s.frameContentSize > 0 && s.nInput != s.frameContentSize {
e.shutdownJobWorkers()
return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput)
}
if s.fullFrameWritten {
e.shutdownJobWorkers()
s.err = ErrEncoderClosed
return nil
}
e.shutdownJobWorkers()
if js.flusherErr != nil {
return js.flusherErr
}
// Write CRC
if e.o.crc {
var tmp [4]byte
_, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0]))
s.nWritten += 4
}
// Add padding
if s.err == nil && e.o.pad > 0 {
add := calcSkippableFrame(s.nWritten, int64(e.o.pad))
frame, err := skippableFrame(js.filling[:0], add, rand.Reader)
if err != nil {
return err
}
_, s.err = s.w.Write(frame)
}
if s.err == nil {
s.err = ErrEncoderClosed
return nil
}
return s.err
}
// EncodeAll will encode all input in src and append it to dst.
// This function can be called concurrently, but each call will only run on a single goroutine.
// If empty input is given, nothing is returned, unless WithZeroFrames is specified.
+53 -16
View File
@@ -14,22 +14,23 @@ type EOption func(*encoderOptions) error
// options retains accumulated state of multiple options.
type encoderOptions struct {
resetOpt bool
concurrent int
level EncoderLevel
single *bool
pad int
blockSize int
windowSize int
crc bool
fullZero bool
noEntropy bool
allLitEntropy bool
customWindow bool
customALEntropy bool
customBlockSize bool
lowMem bool
dict *dict
resetOpt bool
concurrent int
level EncoderLevel
single *bool
pad int
blockSize int
windowSize int
crc bool
fullZero bool
noEntropy bool
allLitEntropy bool
customWindow bool
customALEntropy bool
customBlockSize bool
lowMem bool
dict *dict
concurrentBlocks bool
}
func (o *encoderOptions) setDefault() {
@@ -333,6 +334,42 @@ func WithLowerEncoderMem(b bool) EOption {
}
}
// WithConcurrentBlocks enables job-based parallel compression for streams.
// When enabled and concurrent > 1, input is split into large sections (jobs)
// that are compressed simultaneously by multiple goroutines.
// Each non-first job receives an overlap prefix from the previous job for match context.
// Output is flushed in order, producing a valid single-frame zstd stream.
//
// Currently disabled when used with dictionary encoding.
// Cannot be changed with ResetWithOptions.
func WithConcurrentBlocks(b bool) EOption {
return func(o *encoderOptions) error {
if o.resetOpt && b != o.concurrentBlocks {
return errors.New("WithConcurrentBlocks cannot be changed on Reset")
}
o.concurrentBlocks = b
return nil
}
}
// jobSize returns the input section size per parallel job.
func (o *encoderOptions) jobSize() int {
s := max(o.windowSize*4, 512<<10)
return s
}
// overlapSize returns the overlap prefix size for parallel jobs.
func (o *encoderOptions) overlapSize() int {
switch o.level {
case SpeedBestCompression:
return o.windowSize / 2
case SpeedBetterCompression:
return o.windowSize / 4
default:
return o.windowSize / 8
}
}
// WithEncoderDict allows to register a dictionary that will be used for the encode.
//
// The slice dict must be in the [dictionary format] produced by
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT.
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
//go:build !appengine && !noasm && gc && !noasm
+153
View File
@@ -0,0 +1,153 @@
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
// EXPERIMENTAL arm64 output lowered from an amd64 avo program.
//go:build arm64 && !appengine && !noasm && gc && !noasm
// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int
TEXT ·buildDtable_asm(SB), $0-24
MOVD ctx+8(FP), R1
MOVD s+0(FP), R6
// Load values
MOVBU 4098(R6), R2
MOVD $0, R0
MOVD $1, R16
LSL R2, R16, R16
ORR R16, R0, R0
MOVD (R1), R3
MOVD 16(R1), R5
SUB $1, R0, R7
MOVD 8(R1), R1
MOVHU 4096(R6), R6
// End load values
// Init, lay down lowprob symbols
MOVD $0, R8
JMP init_main_loop_condition
init_main_loop:
ADD R8<<1, R1, R15
MOVH (R15), R9
AND $0xffff, R9, R15
MOVD $-1, R16
AND $0xffff, R16, R16
CMP R16, R15
BNE do_not_update_high_threshold
ADD R7<<3, R5, R15
MOVB R8, 1(R15)
SUB $1, R7, R7
MOVD $0x0000000000000001, R9
do_not_update_high_threshold:
ADD R8<<1, R3, R15
MOVH R9, (R15)
ADD $1, R8, R8
init_main_loop_condition:
CMP R6, R8
BLT init_main_loop
// Spread symbols
// Calculate table step
MOVD R0, R8
LSR $0x01, R8, R8
MOVD R0, R9
LSR $0x03, R9, R9
ADD R9, R8, R8
ADD $3, R8, R8
// Fill add bits values
SUB $1, R0, R9
MOVD $0, R10
MOVD $0, R11
JMP spread_main_loop_condition
spread_main_loop:
MOVD $0, R12
ADD R11<<1, R1, R15
MOVH (R15), R13
JMP spread_inner_loop_condition
spread_inner_loop:
ADD R10<<3, R5, R15
MOVB R11, 1(R15)
adjust_position:
ADD R8, R10, R10
AND R9, R10, R10
CMP R7, R10
BGT adjust_position
ADD $1, R12, R12
spread_inner_loop_condition:
CMP R13, R12
BLT spread_inner_loop
ADD $1, R11, R11
spread_main_loop_condition:
CMP R6, R11
BLT spread_main_loop
TST R10, R10
BEQ spread_check_ok
MOVD ctx+8(FP), R0
MOVD R10, 24(R0)
MOVD $+1, R16
MOVD R16, ret+16(FP)
RET
spread_check_ok:
// Build Decoding table
MOVD $0, R6
build_table_main_table:
ADD R6<<3, R5, R15
MOVBU 1(R15), R1
ADD R1<<1, R3, R15
MOVHU (R15), R7
ADD $1, R7, R8
ADD R1<<1, R3, R15
MOVH R8, (R15)
MOVD R7, R8
CLZ R8, R16
MOVD $63, R8
SUB R16, R8, R8
MOVD R2, R1
SUB R8, R1, R1
LSL R1, R7, R7
SUB R0, R7, R7
ADD R6<<3, R5, R15
MOVB R1, (R15)
ADD R6<<3, R5, R15
MOVH R7, 2(R15)
CMP R0, R7
BLE build_table_check1_ok
MOVD ctx+8(FP), R1
MOVD R7, 24(R1)
MOVD R0, 32(R1)
MOVD $+2, R16
MOVD R16, ret+16(FP)
RET
build_table_check1_ok:
AND $0xff, R1, R15
AND $0xff, R1, R16
TST R16, R15
BNE build_table_check2_ok
AND $0xffff, R7, R15
AND $0xffff, R6, R16
CMP R16, R15
BNE build_table_check2_ok
MOVD ctx+8(FP), R0
MOVD R7, 24(R0)
MOVD R6, 32(R0)
MOVD $+3, R16
MOVD R16, ret+16(FP)
RET
build_table_check2_ok:
ADD $1, R6, R6
CMP R0, R6
BLT build_table_main_table
MOVD $+0, R16
MOVD R16, ret+16(FP)
RET
@@ -1,4 +1,4 @@
//go:build amd64 && !appengine && !noasm && gc
//go:build (amd64 || arm64) && !appengine && !noasm && gc
package zstd
@@ -6,6 +6,10 @@ import (
"fmt"
)
// buildDtable_asm is generated by _generate/gen_fse.go and lowered to each
// architecture (amd64 by goasm, arm64 by the avo arm64 lowering printer). The
// Go side is identical across architectures, so it lives here.
type buildDtableAsmContext struct {
// inputs
stateTable *uint16
@@ -18,7 +22,7 @@ type buildDtableAsmContext struct {
errParam2 uint64
}
// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable.
// buildDtable_asm is an assembly implementation of fseDecoder.buildDtable.
// Function returns non-zero exit code on error.
//
//go:noescape
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !amd64 || appengine || !gc || noasm
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
package zstd
+51 -333
View File
@@ -3,30 +3,47 @@
package zstd
import (
"fmt"
"io"
"github.com/klauspost/compress/internal/cpuinfo"
)
type decodeSyncAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
litRemain int
out []byte
outPosition int
literals []byte
litPosition int
history []byte
windowSize int
ll int // set on error (not for all errors, please refer to _generate/gen.go)
ml int // set on error (not for all errors, please refer to _generate/gen.go)
mo int // set on error (not for all errors, please refer to _generate/gen.go)
// The shared decode/decodeSync/executeSimple wrappers and context structs live
// in seqdec_asm.go; this file only declares the amd64 asm routines and the
// dispatch helpers that pick the BMI2 / non-BMI2 (and 56-bit / safe) variant.
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_amd64 implements the main loop of sequenceDecs in x86 asm.
//
//go:noescape
func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_bmi2 implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_bmi2 implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decodeAsm runs the sequenceDecs decode loop, choosing the BMI2 / 56-bit variant.
func decodeAsm(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext, lte56bits bool) int {
if cpuinfo.HasBMI2() {
if lte56bits {
return sequenceDecs_decode_56_bmi2(s, br, ctx)
}
return sequenceDecs_decode_bmi2(s, br, ctx)
}
if lte56bits {
return sequenceDecs_decode_56_amd64(s, br, ctx)
}
return sequenceDecs_decode_amd64(s, br, ctx)
}
// sequenceDecs_decodeSync_amd64 implements the main loop of sequenceDecs.decodeSync in x86 asm.
@@ -51,273 +68,18 @@ func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *dec
//go:noescape
func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// decode sequences from the stream with the provided history but without a dictionary.
func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
if len(s.dict) > 0 {
return false, nil
}
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize {
return false, nil
}
// FIXME: Using unsafe memory copies leads to rare, random crashes
// with fuzz testing. It is therefore disabled for now.
const useSafe = true
/*
useSafe := false
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc {
useSafe = true
}
if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) {
useSafe = true
}
if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc {
useSafe = true
}
*/
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeSyncAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
iteration: s.nSeqs - 1,
litRemain: len(s.literals),
out: s.out,
outPosition: len(s.out),
literals: s.literals,
windowSize: s.windowSize,
history: hist,
}
s.seqSize = 0
startSize := len(s.out)
var errCode int
// decodeSyncAsm runs the decodeSync loop, choosing the BMI2 / safe variant.
func decodeSyncAsm(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext, safe bool) int {
if cpuinfo.HasBMI2() {
if useSafe {
errCode = sequenceDecs_decodeSync_safe_bmi2(s, br, &ctx)
} else {
errCode = sequenceDecs_decodeSync_bmi2(s, br, &ctx)
}
} else {
if useSafe {
errCode = sequenceDecs_decodeSync_safe_amd64(s, br, &ctx)
} else {
errCode = sequenceDecs_decodeSync_amd64(s, br, &ctx)
if safe {
return sequenceDecs_decodeSync_safe_bmi2(s, br, ctx)
}
return sequenceDecs_decodeSync_bmi2(s, br, ctx)
}
switch errCode {
case noError:
break
case errorMatchLenOfsMismatch:
return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml)
case errorMatchLenTooBig:
return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml)
case errorMatchOffTooBig:
return true, fmt.Errorf("match offset (%d) bigger than current history (%d)",
ctx.mo, ctx.outPosition+len(hist)-startSize)
case errorNotEnoughLiterals:
return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available",
ctx.ll, ctx.litRemain+ctx.ll)
case errorOverread:
return true, io.ErrUnexpectedEOF
case errorNotEnoughSpace:
size := ctx.outPosition + ctx.ll + ctx.ml
if debugDecoder {
println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize)
}
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
default:
return true, fmt.Errorf("sequenceDecs_decode returned erroneous code %d", errCode)
if safe {
return sequenceDecs_decodeSync_safe_amd64(s, br, ctx)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
return true, err
}
s.literals = s.literals[ctx.litPosition:]
t := ctx.outPosition
s.out = s.out[:t]
// Add final literals
s.out = append(s.out, s.literals...)
if debugDecoder {
t += len(s.literals)
if t != len(s.out) {
panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t))
}
}
return true, nil
}
// --------------------------------------------------------------------------------
type decodeAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
seqs []seqVals
litRemain int
}
const noError = 0
// error reported when mo == 0 && ml > 0
const errorMatchLenOfsMismatch = 1
// error reported when ml > maxMatchLen
const errorMatchLenTooBig = 2
// error reported when mo > available history or mo > s.windowSize
const errorMatchOffTooBig = 3
// error reported when the sum of literal lengths exeeceds the literal buffer size
const errorNotEnoughLiterals = 4
// error reported when capacity of `out` is too small
const errorNotEnoughSpace = 5
// error reported when bits are overread.
const errorOverread = 6
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decode sequences from the stream without the provided history.
func (s *sequenceDecs) decode(seqs []seqVals) error {
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
seqs: seqs,
iteration: len(seqs) - 1,
litRemain: len(s.literals),
}
if debugDecoder {
println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream")
}
s.seqSize = 0
lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56
var errCode int
if cpuinfo.HasBMI2() {
if lte56bits {
errCode = sequenceDecs_decode_56_bmi2(s, br, &ctx)
} else {
errCode = sequenceDecs_decode_bmi2(s, br, &ctx)
}
} else {
if lte56bits {
errCode = sequenceDecs_decode_56_amd64(s, br, &ctx)
} else {
errCode = sequenceDecs_decode_amd64(s, br, &ctx)
}
}
if errCode != 0 {
i := len(seqs) - ctx.iteration - 1
switch errCode {
case errorMatchLenOfsMismatch:
ml := ctx.seqs[i].ml
return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml)
case errorMatchLenTooBig:
ml := ctx.seqs[i].ml
return fmt.Errorf("match len (%d) bigger than max allowed length", ml)
case errorNotEnoughLiterals:
ll := ctx.seqs[i].ll
return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll)
case errorOverread:
return io.ErrUnexpectedEOF
}
return fmt.Errorf("sequenceDecs_decode_amd64 returned erroneous code %d", errCode)
}
if ctx.litRemain < 0 {
return fmt.Errorf("literal count is too big: total available %d, total requested %d",
len(s.literals), len(s.literals)-ctx.litRemain)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
if debugDecoder {
println("decode: ", br.remain(), "bits remain on stream. code:", errCode)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
}
return err
}
// --------------------------------------------------------------------------------
type executeAsmContext struct {
seqs []seqVals
seqIndex int
out []byte
history []byte
literals []byte
outPosition int
litPosition int
windowSize int
return sequenceDecs_decodeSync_amd64(s, br, ctx)
}
// sequenceDecs_executeSimple_amd64 implements the main loop of sequenceDecs.executeSimple in x86 asm.
@@ -334,54 +96,10 @@ func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool
//go:noescape
func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool
// executeSimple handles cases when dictionary is not used.
func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error {
// Ensure we have enough output size...
if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) {
addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc
s.out = append(s.out, make([]byte, addBytes)...)
s.out = s.out[:len(s.out)-addBytes]
// executeSimpleAsm runs the executeSimple loop, choosing the safe variant.
func executeSimpleAsm(ctx *executeAsmContext, safe bool) bool {
if safe {
return sequenceDecs_executeSimple_safe_amd64(ctx)
}
if debugDecoder {
printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize)
}
var t = len(s.out)
out := s.out[:t+s.seqSize]
ctx := executeAsmContext{
seqs: seqs,
seqIndex: 0,
out: out,
history: hist,
outPosition: t,
litPosition: 0,
literals: s.literals,
windowSize: s.windowSize,
}
var ok bool
if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc {
ok = sequenceDecs_executeSimple_safe_amd64(&ctx)
} else {
ok = sequenceDecs_executeSimple_amd64(&ctx)
}
if !ok {
return fmt.Errorf("match offset (%d) bigger than current history (%d)",
seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist))
}
s.literals = s.literals[ctx.litPosition:]
t = ctx.outPosition
// Add final literals
copy(out[t:], s.literals)
if debugDecoder {
t += len(s.literals)
if t != len(out) {
panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize))
}
}
s.out = out
return nil
return sequenceDecs_executeSimple_amd64(ctx)
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by command: go run gen.go -out ../seqdec_amd64.s -pkg=zstd. DO NOT EDIT.
// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
//go:build !appengine && !noasm && gc && !noasm
+70
View File
@@ -0,0 +1,70 @@
//go:build arm64 && !appengine && !noasm && gc
package zstd
// The shared decode/decodeSync/executeSimple wrappers and context structs live
// in seqdec_asm.go; this file only declares the arm64 asm routines (generated
// by the avo arm64 lowering printer) and the dispatch helpers. arm64 has no
// BMI2, so each helper selects only between the 56-bit / safe variants.
// sequenceDecs_decode_arm64 implements the main loop of sequenceDecs in arm64 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_arm64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_arm64 implements the main loop of sequenceDecs in arm64 asm.
//
//go:noescape
func sequenceDecs_decode_56_arm64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decodeAsm runs the sequenceDecs decode loop, choosing the 56-bit variant.
func decodeAsm(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext, lte56bits bool) int {
if lte56bits {
return sequenceDecs_decode_56_arm64(s, br, ctx)
}
return sequenceDecs_decode_arm64(s, br, ctx)
}
// sequenceDecs_decodeSync_arm64 implements the main loop of sequenceDecs.decodeSync in arm64 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decodeSync_arm64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// sequenceDecs_decodeSync_safe_arm64 does the same as above, but does not write more than output buffer.
//
//go:noescape
func sequenceDecs_decodeSync_safe_arm64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// decodeSyncAsm runs the decodeSync loop, choosing the safe variant.
func decodeSyncAsm(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext, safe bool) int {
if safe {
return sequenceDecs_decodeSync_safe_arm64(s, br, ctx)
}
return sequenceDecs_decodeSync_arm64(s, br, ctx)
}
// sequenceDecs_executeSimple_arm64 implements the main loop of sequenceDecs.executeSimple in arm64 asm.
//
// Returns false if a match offset is too big.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_executeSimple_arm64(ctx *executeAsmContext) bool
// Same as above, but with safe memcopies
//
//go:noescape
func sequenceDecs_executeSimple_safe_arm64(ctx *executeAsmContext) bool
// executeSimpleAsm runs the executeSimple loop, choosing the safe variant.
func executeSimpleAsm(ctx *executeAsmContext, safe bool) bool {
if safe {
return sequenceDecs_executeSimple_safe_arm64(ctx)
}
return sequenceDecs_executeSimple_arm64(ctx)
}
File diff suppressed because it is too large. Load diff
+289
View File
@@ -0,0 +1,289 @@
//go:build (amd64 || arm64) && !appengine && !noasm && gc
package zstd
import (
"fmt"
"io"
)
// This file holds the parts of the assembly sequence decoder that are identical
// across architectures: the context structs exchanged with the asm, the error
// codes, and the decode/decodeSync/executeSimple wrappers. Each architecture
// supplies the small dispatch helpers (decodeAsm, decodeSyncAsm,
// executeSimpleAsm) that select the concrete asm routine — amd64 also chooses a
// BMI2 variant, arm64 has a single implementation.
type decodeSyncAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
litRemain int
out []byte
outPosition int
literals []byte
litPosition int
history []byte
windowSize int
ll int // set on error (not for all errors, please refer to _generate/gen.go)
ml int // set on error (not for all errors, please refer to _generate/gen.go)
mo int // set on error (not for all errors, please refer to _generate/gen.go)
}
type decodeAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
seqs []seqVals
litRemain int
}
type executeAsmContext struct {
seqs []seqVals
seqIndex int
out []byte
history []byte
literals []byte
outPosition int
litPosition int
windowSize int
}
const noError = 0
// error reported when mo == 0 && ml > 0
const errorMatchLenOfsMismatch = 1
// error reported when ml > maxMatchLen
const errorMatchLenTooBig = 2
// error reported when mo > available history or mo > s.windowSize
const errorMatchOffTooBig = 3
// error reported when the sum of literal lengths exeeceds the literal buffer size
const errorNotEnoughLiterals = 4
// error reported when capacity of `out` is too small
const errorNotEnoughSpace = 5
// error reported when bits are overread.
const errorOverread = 6
// decode sequences from the stream with the provided history but without a dictionary.
func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
if len(s.dict) > 0 {
return false, nil
}
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize {
return false, nil
}
// FIXME: Using unsafe memory copies leads to rare, random crashes
// with fuzz testing. It is therefore disabled for now.
const useSafe = true
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeSyncAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
iteration: s.nSeqs - 1,
litRemain: len(s.literals),
out: s.out,
outPosition: len(s.out),
literals: s.literals,
windowSize: s.windowSize,
history: hist,
}
s.seqSize = 0
startSize := len(s.out)
errCode := decodeSyncAsm(s, br, &ctx, useSafe)
switch errCode {
case noError:
break
case errorMatchLenOfsMismatch:
return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml)
case errorMatchLenTooBig:
return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml)
case errorMatchOffTooBig:
return true, fmt.Errorf("match offset (%d) bigger than current history (%d)",
ctx.mo, ctx.outPosition+len(hist)-startSize)
case errorNotEnoughLiterals:
return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available",
ctx.ll, ctx.litRemain+ctx.ll)
case errorOverread:
return true, io.ErrUnexpectedEOF
case errorNotEnoughSpace:
size := ctx.outPosition + ctx.ll + ctx.ml
if debugDecoder {
println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize)
}
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
default:
return true, fmt.Errorf("sequenceDecs_decode returned erroneous code %d", errCode)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
return true, err
}
s.literals = s.literals[ctx.litPosition:]
t := ctx.outPosition
s.out = s.out[:t]
// Add final literals
s.out = append(s.out, s.literals...)
if debugDecoder {
t += len(s.literals)
if t != len(s.out) {
panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t))
}
}
return true, nil
}
// decode sequences from the stream without the provided history.
func (s *sequenceDecs) decode(seqs []seqVals) error {
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
seqs: seqs,
iteration: len(seqs) - 1,
litRemain: len(s.literals),
}
if debugDecoder {
println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream")
}
s.seqSize = 0
lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56
errCode := decodeAsm(s, br, &ctx, lte56bits)
if errCode != 0 {
i := len(seqs) - ctx.iteration - 1
switch errCode {
case errorMatchLenOfsMismatch:
ml := ctx.seqs[i].ml
return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml)
case errorMatchLenTooBig:
ml := ctx.seqs[i].ml
return fmt.Errorf("match len (%d) bigger than max allowed length", ml)
case errorNotEnoughLiterals:
ll := ctx.seqs[i].ll
return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll)
case errorOverread:
return io.ErrUnexpectedEOF
}
return fmt.Errorf("sequenceDecs_decode_amd64 returned erroneous code %d", errCode)
}
if ctx.litRemain < 0 {
return fmt.Errorf("literal count is too big: total available %d, total requested %d",
len(s.literals), len(s.literals)-ctx.litRemain)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
if debugDecoder {
println("decode: ", br.remain(), "bits remain on stream. code:", errCode)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
}
return err
}
// executeSimple handles cases when dictionary is not used.
func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error {
// Ensure we have enough output size...
if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) {
addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc
s.out = append(s.out, make([]byte, addBytes)...)
s.out = s.out[:len(s.out)-addBytes]
}
if debugDecoder {
printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize)
}
var t = len(s.out)
out := s.out[:t+s.seqSize]
ctx := executeAsmContext{
seqs: seqs,
seqIndex: 0,
out: out,
history: hist,
outPosition: t,
litPosition: 0,
literals: s.literals,
windowSize: s.windowSize,
}
// useSafe avoids overwriting the output buffer when the literals slice has
// not been allocated with the required over-allocation slack.
useSafe := cap(s.literals) < len(s.literals)+compressedBlockOverAlloc
ok := executeSimpleAsm(&ctx, useSafe)
if !ok {
return fmt.Errorf("match offset (%d) bigger than current history (%d)",
seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist))
}
s.literals = s.literals[ctx.litPosition:]
t = ctx.outPosition
// Add final literals
copy(out[t:], s.literals)
if debugDecoder {
t += len(s.literals)
if t != len(out) {
panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize))
}
}
s.out = out
return nil
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !amd64 || appengine || !gc || noasm
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
package zstd
+4 -3
View File
@@ -334,9 +334,10 @@ func decodeSnappy(blk *blockEnc, src []byte) error {
return errUnsupportedLiteralLength
}
//if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s {
// return ErrSnappyCorrupt
//}
if length > len(src)-s {
println("length > len(src)-s", length, len(src)-s)
return ErrSnappyCorrupt
}
blk.literals = append(blk.literals, src[s:s+length]...)
//println(length, "litLen")
+15
View File
@@ -0,0 +1,15 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: en-US
reviews:
# Skip the vendored SQLite amalgamation. These files are copied verbatim from
# upstream SQLite (see the License section in README.md) and are not code that
# this project authors or reviews.
path_filters:
- "!sqlite3-binding.c"
- "!sqlite3-binding.h"
- "!sqlite3ext.h"
auto_review:
enabled: true
drafts: false
chat:
auto_reply: true
+11
View File
@@ -7,6 +7,17 @@ go-sqlite3
[![codecov](https://codecov.io/gh/mattn/go-sqlite3/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-sqlite3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3)
## Sponsors
This project is proudly sponsored by:
<a href="https://coderabbit.link/mattn">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://victorious-bubble-f69a016683.media.strapiapp.com/White_Typemark_79b9189d19.svg">
<img src="https://victorious-bubble-f69a016683.media.strapiapp.com/Orange_Typemark_43bf516c9d.svg" alt="CodeRabbit" width="320">
</picture>
</a>
Latest stable version is v1.14 or later, not v2.
# Description
+31 -23
View File
@@ -34,8 +34,8 @@ import (
)
//export callbackTrampoline
func callbackTrampoline(ctx *C.sqlite3_context, argc int, argv **C.sqlite3_value) {
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
func callbackTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) {
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)]
fi := lookupHandle(C.sqlite3_user_data(ctx)).(*functionInfo)
fi.Call(ctx, args)
}
@@ -60,9 +60,9 @@ func compareTrampoline(handlePtr unsafe.Pointer, la C.int, a *C.char, lb C.int,
}
//export commitHookTrampoline
func commitHookTrampoline(handle unsafe.Pointer) int {
func commitHookTrampoline(handle unsafe.Pointer) C.int {
callback := lookupHandle(handle).(func() int)
return callback()
return C.int(callback())
}
//export rollbackHookTrampoline
@@ -72,23 +72,23 @@ func rollbackHookTrampoline(handle unsafe.Pointer) {
}
//export updateHookTrampoline
func updateHookTrampoline(handle unsafe.Pointer, op int, db *C.char, table *C.char, rowid int64) {
func updateHookTrampoline(handle unsafe.Pointer, op C.int, db *C.char, table *C.char, rowid int64) {
callback := lookupHandle(handle).(func(int, string, string, int64))
callback(op, C.GoString(db), C.GoString(table), rowid)
callback(int(op), C.GoString(db), C.GoString(table), rowid)
}
//export authorizerTrampoline
func authorizerTrampoline(handle unsafe.Pointer, op int, arg1 *C.char, arg2 *C.char, arg3 *C.char) int {
func authorizerTrampoline(handle unsafe.Pointer, op C.int, arg1 *C.char, arg2 *C.char, arg3 *C.char) C.int {
callback := lookupHandle(handle).(func(int, string, string, string) int)
return callback(op, C.GoString(arg1), C.GoString(arg2), C.GoString(arg3))
return C.int(callback(int(op), C.GoString(arg1), C.GoString(arg2), C.GoString(arg3)))
}
//export preUpdateHookTrampoline
func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op C.int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
hval := lookupHandleVal(handle)
data := SQLitePreUpdateData{
Conn: hval.db,
Op: op,
Op: int(op),
DatabaseName: C.GoString(db),
TableName: C.GoString(table),
OldRowID: oldrowid,
@@ -260,6 +260,16 @@ func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) {
}
}
// callbackArgConvert returns conv as-is when the parameter type is the
// canonical type conv produces, and wraps it with a cast for named types
// (e.g. time.Duration), which reflect.Call would otherwise panic on.
func callbackArgConvert(conv callbackArgConverter, typ, canonical reflect.Type) callbackArgConverter {
if typ == canonical {
return conv
}
return callbackArgCast{conv, typ}.Run
}
func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
switch typ.Kind() {
case reflect.Interface:
@@ -271,18 +281,18 @@ func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
if typ.Elem().Kind() != reflect.Uint8 {
return nil, errors.New("the only supported slice type is []byte")
}
return callbackArgBytes, nil
return callbackArgConvert(callbackArgBytes, typ, reflect.TypeOf([]byte(nil))), nil
case reflect.String:
return callbackArgString, nil
return callbackArgConvert(callbackArgString, typ, reflect.TypeOf("")), nil
case reflect.Bool:
return callbackArgBool, nil
return callbackArgConvert(callbackArgBool, typ, reflect.TypeOf(false)), nil
case reflect.Int64:
return callbackArgInt64, nil
return callbackArgConvert(callbackArgInt64, typ, reflect.TypeOf(int64(0))), nil
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
c := callbackArgCast{callbackArgInt64, typ}
return c.Run, nil
case reflect.Float64:
return callbackArgFloat64, nil
return callbackArgConvert(callbackArgFloat64, typ, reflect.TypeOf(float64(0))), nil
case reflect.Float32:
c := callbackArgCast{callbackArgFloat64, typ}
return c.Run, nil
@@ -326,8 +336,7 @@ func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
v = v.Convert(reflect.TypeOf(int64(0)))
case reflect.Bool:
b := v.Interface().(bool)
if b {
if v.Bool() {
v = reflect.ValueOf(int64(1))
} else {
v = reflect.ValueOf(int64(0))
@@ -336,7 +345,7 @@ func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
return fmt.Errorf("cannot convert %s to INTEGER", v.Type())
}
C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Interface().(int64)))
C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Int()))
return nil
}
@@ -349,7 +358,7 @@ func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error {
return fmt.Errorf("cannot convert %s to FLOAT", v.Type())
}
C.sqlite3_result_double(ctx, C.double(v.Interface().(float64)))
C.sqlite3_result_double(ctx, C.double(v.Float()))
return nil
}
@@ -357,11 +366,10 @@ func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error {
if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 {
return fmt.Errorf("cannot convert %s to BLOB", v.Type())
}
i := v.Interface()
if i == nil || len(i.([]byte)) == 0 {
bs := v.Bytes()
if len(bs) == 0 {
C.sqlite3_result_null(ctx)
} else {
bs := i.([]byte)
if i64 && len(bs) > math.MaxInt32 {
C.sqlite3_result_error_toobig(ctx)
return nil
@@ -375,7 +383,7 @@ func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error {
if v.Type().Kind() != reflect.String {
return fmt.Errorf("cannot convert %s to TEXT", v.Type())
}
s := v.Interface().(string)
s := v.String()
if i64 && len(s) > math.MaxInt32 {
C.sqlite3_result_error_toobig(ctx)
return nil
+515 -278
View File
File diff suppressed because it is too large. Load diff
+9 -7
View File
@@ -147,12 +147,12 @@ extern "C" {
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION "3.53.2"
#define SQLITE_VERSION_NUMBER 3053002
#define SQLITE_SOURCE_ID "2026-06-03 19:12:13 d6e03d8c777cfa2d35e3b60d8ec3e0187f3e9f99d8e2ee9cac695fd6fcdf1a24"
#define SQLITE_VERSION "3.53.3"
#define SQLITE_VERSION_NUMBER 3053003
#define SQLITE_SOURCE_ID "2026-06-26 20:14:12 d4c0e51e4aeb96955b99185ab9cde75c339e2c29c3f3f12428d364a10d782c62"
#define SQLITE_SCM_BRANCH "branch-3.53"
#define SQLITE_SCM_TAGS "release version-3.53.2"
#define SQLITE_SCM_DATETIME "2026-06-03T19:12:13.350Z"
#define SQLITE_SCM_TAGS "release version-3.53.3"
#define SQLITE_SCM_DATETIME "2026-06-26T20:14:12.354Z"
/*
** CAPI3REF: Run-Time Library Version Numbers
@@ -4367,7 +4367,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
** or in an ORDER BY or GROUP BY clause.</dd>)^
**
** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
** <dd>The maximum depth of the parse tree on any expression.</dd>)^
** <dd>The maximum depth of the parse tree on any expression and
** the maximum nesting depth for subqueries and VIEWs</dd>)^
**
** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
** <dd>The maximum depth of the LALR(1) parser stack used to analyze
@@ -4398,7 +4399,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
** <dd>The maximum index number of any [parameter] in an SQL statement.)^
**
** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
** <dd>The maximum depth of recursion for triggers.</dd>)^
** <dd>The maximum depth of recursion for triggers, and the maximum
** nesting depth for separate triggers.</dd>)^
**
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
** <dd>The maximum number of auxiliary worker threads that a single
+87 -73
View File
@@ -445,12 +445,12 @@ type SQLiteDriver struct {
// SQLiteConn implements driver.Conn.
type SQLiteConn struct {
mu sync.Mutex
db *C.sqlite3
loc *time.Location
txlock string
funcs []*functionInfo
aggregators []*aggInfo
mu sync.Mutex
db *C.sqlite3
loc *time.Location
txlock string
funcs []*functionInfo
aggregators []*aggInfo
// Prepared-statement cache. The slice is allocated at Open with a
// fixed capacity equal to the configured cache size; cap bounds the
// cache, len is the live count, and entries are ordered LRU-first
@@ -1595,6 +1595,20 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
return nil, errors.New("sqlite succeeded without returning a database")
}
// Create connection to SQLite
conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
if stmtCacheSize > 0 {
conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize)
conn.stmtCacheEnabled = true
}
// fail closes the connection so no error path leaks the database
// handle or any callback handles registered on it.
fail := func(err error) (driver.Conn, error) {
conn.Close()
return nil, err
}
exec := func(s string) error {
cs := C.CString(s)
rv := C.sqlite3_exec(db, cs, nil, nil, nil)
@@ -1607,8 +1621,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Busy timeout
if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
// USER AUTHENTICATION
@@ -1633,66 +1646,59 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// NO => Continue
//
// Create connection to SQLite
conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
if stmtCacheSize > 0 {
conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize)
conn.stmtCacheEnabled = true
}
// Password Cipher has to be registered before authentication
if len(authCrypt) > 0 {
switch strings.ToUpper(authCrypt) {
case "SHA1":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA1: %s", err))
}
case "SSHA1":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA1: %s", err))
}
case "SHA256":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA256: %s", err))
}
case "SSHA256":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA256: %s", err))
}
case "SHA384":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA384: %s", err))
}
case "SSHA384":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA384: %s", err))
}
case "SHA512":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA512: %s", err))
}
case "SSHA512":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA512: %s", err))
}
}
}
// Preform Authentication
if err := conn.Authenticate(authUser, authPass); err != nil {
return nil, err
return fail(err)
}
// Register: authenticate
@@ -1710,7 +1716,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// If the SQLITE_USER table is not present in the database file, then
// this interface is a harmless no-op returnning SQLITE_OK.
if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_add
@@ -1723,7 +1729,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// for any ATTACH-ed databases. Any call to AuthUserAdd by a
// non-admin user results in an error.
if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_change
@@ -1733,7 +1739,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// credentials or admin privilege setting. No user may change their own
// admin privilege setting.
if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_delete
@@ -1743,13 +1749,13 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// the database cannot be converted into a no-authentication-required
// database.
if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
return nil, err
return fail(err)
}
// Register: auth_enabled
// auth_enabled can be used to check if user authentication is enabled
if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
return nil, err
return fail(err)
}
// Auto Vacuum
@@ -1760,8 +1766,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// and activating user authentication creates the internal table `sqlite_user`.
if autoVacuum > -1 {
if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1771,17 +1776,17 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// has provided an username and password within the DSN.
// We are not allowed to continue.
if len(authUser) == 0 {
return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
return fail(fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'"))
}
if len(authPass) == 0 {
return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
return fail(fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'"))
}
// Check if User Authentication is Enabled
authExists := conn.AuthEnabled()
if !authExists {
if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
return nil, err
return fail(err)
}
}
}
@@ -1789,40 +1794,35 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Case Sensitive LIKE
if caseSensitiveLike > -1 {
if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Defer Foreign Keys
if deferForeignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Foreign Keys
if foreignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Ignore CHECK Constraints
if ignoreCheckConstraints > -1 {
if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Journal Mode
if journalMode != "" {
if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1830,23 +1830,20 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Because the default is NORMAL and this is not changed in this package
// by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
// Query Only
if queryOnly > -1 {
if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Recursive Triggers
if recursiveTriggers > -1 {
if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1857,8 +1854,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// you can compile with secure_delete 'ON' and disable it for a specific database connection.
if secureDelete != "DEFAULT" {
if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1866,37 +1862,32 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
//
// Because default is NORMAL this statement is always executed
if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
conn.Close()
return nil, err
return fail(err)
}
// Writable Schema
if writableSchema > -1 {
if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Cache Size
if cacheSize != nil {
if err := exec(fmt.Sprintf("PRAGMA cache_size = %d;", *cacheSize)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
if len(d.Extensions) > 0 {
if err := conn.loadExtensions(d.Extensions); err != nil {
conn.Close()
return nil, err
return fail(err)
}
}
if d.ConnectHook != nil {
if err := d.ConnectHook(conn); err != nil {
conn.Close()
return nil, err
return fail(err)
}
}
runtime.SetFinalizer(conn, (*SQLiteConn).Close)
@@ -1970,6 +1961,10 @@ func (c *SQLiteConn) putCachedStmt(s *SQLiteStmt) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.putCachedStmtLocked(s)
}
func (c *SQLiteConn) putCachedStmtLocked(s *SQLiteStmt) bool {
if c.db == nil {
return false
}
@@ -2164,12 +2159,20 @@ func (s *SQLiteStmt) Close() error {
s.c = nil
return nil
}
if !conn.dbConnOpen() {
if s.cacheKey != "" {
conn.mu.Lock()
if conn.db == nil {
conn.mu.Unlock()
return errors.New("sqlite statement with already closed database connection")
}
if conn.putCachedStmtLocked(s) {
conn.mu.Unlock()
return nil
}
conn.mu.Unlock()
} else if !conn.dbConnOpen() {
return errors.New("sqlite statement with already closed database connection")
}
if s.cacheKey != "" && conn.putCachedStmt(s) {
return nil
}
s.s = nil
s.c = nil
rv := C.sqlite3_finalize(stmt)
@@ -2282,6 +2285,17 @@ func stmtArgs(args []driver.NamedValue, start, na int) []driver.NamedValue {
return stmtArgs
}
// bindError converts a non-OK return code from bindValue into an error.
// The synthetic SQLITE_MISUSE returned for unsupported Go types is never
// recorded in the database handle, so lastError may report no error; fall
// back to an explicit message instead of silently ignoring the failure.
func (s *SQLiteStmt) bindError(v driver.Value) error {
if err := s.c.lastError(); err != nil {
return err
}
return fmt.Errorf("sqlite3: unsupported bind type %T", v)
}
func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
rv := C._sqlite3_reset_clear(s.s)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
@@ -2301,7 +2315,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
n := C.int(arg.Ordinal)
rv = bindValue(s.s, n, arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
}
return nil
@@ -2311,7 +2325,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
if arg.Name == "" {
rv = bindValue(s.s, C.int(arg.Ordinal), arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
continue
}
@@ -2322,7 +2336,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
}
rv = bindValue(s.s, C.int(idx), arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
}
}
+3 -3
View File
@@ -74,11 +74,11 @@ func (c *SQLiteConn) loadExtension(lib string, entry *string) error {
}
var errMsg *C.char
defer C.sqlite3_free(unsafe.Pointer(errMsg))
rv := C.sqlite3_load_extension(c.db, clib, centry, &errMsg)
if rv != C.SQLITE_OK {
return errors.New(C.GoString(errMsg))
err := errors.New(C.GoString(errMsg))
C.sqlite3_free(unsafe.Pointer(errMsg))
return err
}
return nil
+6 -2
View File
@@ -59,13 +59,17 @@ func (d *SQLitePreUpdateData) row(dest []any, new bool) error {
for i := 0; i < d.Count() && i < len(dest); i++ {
var val *C.sqlite3_value
var src any
var rc C.int
// Initially I tried making this just a function pointer argument, but
// it's absurdly complicated to pass C function pointers.
if new {
C.sqlite3_preupdate_new(d.Conn.db, C.int(i), &val)
rc = C.sqlite3_preupdate_new(d.Conn.db, C.int(i), &val)
} else {
C.sqlite3_preupdate_old(d.Conn.db, C.int(i), &val)
rc = C.sqlite3_preupdate_old(d.Conn.db, C.int(i), &val)
}
if rc != C.SQLITE_OK {
return Error{Code: ErrNo(rc)}
}
switch C.sqlite3_value_type(val) {
+3
View File
@@ -60,6 +60,9 @@ func (c *SQLiteConn) Deserialize(b []byte, schema string) error {
defer C.free(unsafe.Pointer(zSchema))
tmpBuf := (*C.uchar)(C.sqlite3_malloc64(C.sqlite3_uint64(len(b))))
if tmpBuf == nil && len(b) > 0 {
return fmt.Errorf("deserialize failed: out of memory")
}
copy(unsafe.Slice((*byte)(unsafe.Pointer(tmpBuf)), len(b)), b)
rc := C.sqlite3_deserialize(c.db, zSchema, tmpBuf, C.sqlite3_int64(len(b)),
+3
View File
@@ -113,6 +113,9 @@ uintptr_t goVOpen(void *pVTab, char **pzErr);
static int cXOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) {
void *vTabCursor = (void *)goVOpen(((goVTab*)pVTab)->vTab, &(pVTab->zErrMsg));
if (!vTabCursor) {
return SQLITE_ERROR;
}
goVTabCursor *pCursor = (goVTabCursor *)sqlite3_malloc(sizeof(goVTabCursor));
if (!pCursor) {
return SQLITE_NOMEM;
@@ -25,6 +25,7 @@ import (
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
@@ -47,6 +48,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -69,6 +71,7 @@ type config struct {
AvailableXS map[string]uint32 `mapstructure:"available_checksums" docs:"nil;List of available checksums."`
CustomMimeTypesJSON string `mapstructure:"custom_mimetypes_json" docs:"nil;An optional mapping file with the list of supported custom file extensions and corresponding mime types."`
MountID string `mapstructure:"mount_id"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
UploadExpiration int64 `mapstructure:"upload_expiration" docs:"0;Duration for how long uploads will be valid."`
Events eventconfig `mapstructure:"events" docs:"0;Event stream configuration"`
}
@@ -106,6 +109,7 @@ func (c *config) init() {
type Service struct {
conf *config
Storage storage.FS
Coordinator upload.Coordinator
dataServerURL *url.URL
availableXS []*provider.ResourceChecksumPriority
}
@@ -175,11 +179,33 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
c.init()
fs, err := getFS(c, log)
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
fs, err := getFS(c, evstream, log)
if err != nil {
return nil, err
}
// Build the coordinator-owned session store. UploadDirectory (service level)
// takes precedence over the driver root, so rootless drivers can still get a
// coordinator. The store points at the same root as the driver's data path so
// it can read the sessions the coordinator writes (decomposedfs on-disk format).
store := upload.NewFileStoreFromConfig(c.UploadDirectory, c.Drivers[c.Driver], log)
if store == nil {
return nil, fmt.Errorf("storageprovider: cannot determine upload directory, set upload_directory in config or driver root")
}
if err := store.Setup(); err != nil {
return nil, fmt.Errorf("storageprovider: upload directory setup failed: %w", err)
}
// Deliberately no StartPostprocessing here: this service initiates uploads but
// never receives the bytes, so it has nothing to hand to postprocessing or to
// commit afterwards. That belongs to the data provider, which owns the PUT and
// TUS paths.
coordinator := upload.NewCoordinator(fs, store, filepath.Join(store.Root(), "uploads"), evstream)
// parse data server url
u, err := url.Parse(c.DataServerURL)
if err != nil {
@@ -205,6 +231,7 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
service := &Service{
conf: c,
Storage: fs,
Coordinator: coordinator,
dataServerURL: u,
availableXS: xsTypes,
}
@@ -427,7 +454,7 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
metadata["expires"] = strconv.Itoa(int(expirationTimestamp.Seconds))
}
uploadIDs, err := s.Storage.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
uploadIDs, err := s.Coordinator.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
if err != nil {
var st *rpc.Status
switch err.(type) {
@@ -452,6 +479,8 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
st = status.NewFailedPrecondition(ctx, err, "failed precondition")
case errtypes.Locked:
st = status.NewLocked(ctx, "locked")
case errtypes.IsTooEarly:
st = status.NewTooEarly(ctx, err.Error())
default:
st = status.NewInternal(ctx, "error getting upload id: "+err.Error())
}
@@ -1264,12 +1293,7 @@ func (s *Service) addMissingStorageProviderID(resourceID *provider.ResourceId, s
}
}
func getFS(c *config, log *zerolog.Logger) (storage.FS, error) {
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
func getFS(c *config, evstream events.Stream, log *zerolog.Logger) (storage.FS, error) {
if f, ok := registry.NewFuncs[c.Driver]; ok {
driverConf := c.Drivers[c.Driver]
driverConf["mount_id"] = c.MountID // pass the mount id to the driver
@@ -21,6 +21,7 @@ package dataprovider
import (
"fmt"
"net/http"
"path/filepath"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog"
@@ -33,6 +34,7 @@ import (
"github.com/owncloud/reva/v2/pkg/rhttp/router"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
pkgupload "github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -51,6 +53,7 @@ type config struct {
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
NatsUsername string `mapstructure:"nats_username"`
NatsPassword string `mapstructure:"nats_password"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver root. Required for drivers without a local root."`
}
func (c *config) init() {
@@ -104,7 +107,27 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
return nil, err
}
dataTXs, err := getDataTXs(conf, fs, evstream, log)
// The data provider finishes uploads that the storage provider initiated, so
// its store must resolve to the same upload directory.
store := pkgupload.NewFileStoreFromConfig(conf.UploadDirectory, conf.Drivers[conf.Driver], log)
if store == nil {
return nil, fmt.Errorf("dataprovider: cannot determine upload directory, set upload_directory in config or driver root")
}
if err := store.Setup(); err != nil {
return nil, fmt.Errorf("dataprovider: upload directory setup failed: %w", err)
}
coord := pkgupload.NewCoordinator(fs, store, filepath.Join(store.Root(), "uploads"), evstream)
// This is the service that receives the bytes, so it is the one that hands them
// to postprocessing and commits them once the verdict comes back. Without this
// the coordinator commits inline and uploads are never scanned.
if ac := pkgupload.AsyncConfFromDriverConf(conf.Drivers[conf.Driver]); ac.Enabled {
if err := coord.StartPostprocessing(evstream, ac.ConsumerGroup, ac.MountID, ac.NumConsumers); err != nil {
return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err)
}
}
dataTXs, err := getDataTXs(conf, coord, fs, evstream, log)
if err != nil {
return nil, err
}
@@ -126,7 +149,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er
return nil, fmt.Errorf("driver not found: %s", c.Driver)
}
func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
func getDataTXs(c *config, coord pkgupload.Coordinator, driver storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
if c.DataTXs == nil {
c.DataTXs = make(map[string]map[string]interface{})
}
@@ -146,7 +169,7 @@ func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerol
for t := range c.DataTXs {
if f, ok := datatxregistry.NewFuncs[t]; ok {
if tx, err := f(c.DataTXs[t], publisher, log); err == nil {
if handler, err := tx.Handler(fs); err == nil {
if handler, err := tx.Handler(coord, driver); err == nil {
txs[t] = handler
}
}
@@ -319,7 +319,11 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http.
sReq.Ref.Path = uReq.Ref.GetPath()
sReq.Ref.ResourceId = nil
} else {
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil {
// A new file has no node id until the upload finishes, which is after the
// data server wrote this header, so it may be absent. sReq.Ref then keeps
// the path-based reference it was built with, which already names the
// file and stats just as well.
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil && resid.GetOpaqueId() != "" {
sReq.Ref = &provider.Reference{
ResourceId: &resid,
}
+85 -5
View File
@@ -253,7 +253,10 @@ func (d *driver) CreateDir(ctx context.Context, ref *provider.Reference) (*stora
}
func (d *driver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
client, _, rel, err := d.webdavClient(ctx, nil, ref)
// The coordinator rolls back a failed upload from the tusd finish path, which
// carries no request auth token, so the share must be resolved as the service
// account on the executant's behalf.
client, _, rel, err := d.serviceWebdavClient(ctx, ref)
if err != nil {
return nil, err
}
@@ -264,14 +267,28 @@ func (d *driver) Delete(ctx context.Context, ref *provider.Reference) (*storage.
}
func (d *driver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
client, _, rel, err := d.webdavClient(ctx, nil, ref)
// The coordinator calls this from the upload finish path, which runs under
// tusd with no request auth token, so the share must be resolved as the
// service account on the executant's behalf.
client, _, rel, err := d.serviceWebdavClient(ctx, ref)
if err != nil {
return nil, err
}
if err := client.Write(rel, []byte{}, 0); err != nil {
return nil, err
}
return &storage.TouchFileResult{}, nil
// The coordinator threads ResourceID into the session so the following
// CommitUpload can address the file, so return the real ids rather than an
// empty result. rel is the remote path, encoded the way GetMD encodes it.
shareID, _ := shareInfoFromReference(ref)
return &storage.TouchFileResult{
SpaceID: shareID.GetOpaqueId(),
ResourceID: &provider.ResourceId{
StorageId: utils.OCMStorageProviderID,
SpaceId: shareID.GetOpaqueId(),
OpaqueId: base64.StdEncoding.EncodeToString([]byte(filepath.Join("/", rel))),
},
}, nil
}
func (d *driver) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
@@ -347,6 +364,44 @@ func convertStatToResourceInfo(ref *provider.Reference, f fs.FileInfo, share *oc
return &ri, nil
}
// extractLock reads the DAV:lockdiscovery property and returns the active lock,
// or nil when the resource carries no usable lock.
//
// gowebdav's Props.GetString formats a missing key as the string "<nil>", so an
// absent lockdiscovery cannot be told apart by emptiness. Instead we require the
// value to parse as <d:activelock> and to carry a lock token: a lock we cannot
// name is one the caller could never match against its own, so treating it as
// absent is the only useful reading.
func extractLock(props gowebdav.Props) *provider.Lock {
raw := props.GetString(xml.Name{Space: "DAV:", Local: "lockdiscovery"})
// Element names are matched on their local part only: the value is the raw
// innerxml of lockdiscovery, so the xmlns:d declaration that bound the "d"
// prefix stayed behind on the enclosing element and the prefix is unbound
// here.
var al struct {
LockScope struct {
Exclusive *struct{} `xml:"exclusive"`
Shared *struct{} `xml:"shared"`
} `xml:"lockscope"`
LockToken struct {
Href string `xml:"href"`
} `xml:"locktoken"`
}
if err := xml.Unmarshal([]byte(raw), &al); err != nil {
return nil
}
if al.LockToken.Href == "" {
return nil
}
lockType := provider.LockType_LOCK_TYPE_EXCL
if al.LockScope.Shared != nil && al.LockScope.Exclusive == nil {
lockType = provider.LockType_LOCK_TYPE_SHARED
}
return &provider.Lock{LockId: al.LockToken.Href, Type: lockType}
}
func extractChecksum(props gowebdav.Props) *provider.ResourceChecksum {
checksums := props.GetString(xml.Name{Space: "http://owncloud.org/ns", Local: "checksums"})
if checksums == "" {
@@ -534,12 +589,29 @@ func (d *driver) GetLock(ctx context.Context, ref *provider.Reference) (*provide
return nil, err
}
token, err := client.GetLock(rel)
// gowebdav's GetLock cannot be used: it stats with a fixed property set that
// omits lockdiscovery, so it reports the same value whatever the lock state.
// getetag is requested alongside because an unlocked resource returns
// lockdiscovery in a 404 propstat, and gowebdav only reads the 200 one — with
// no other property to carry it, that propstat would be empty and the stat
// would fail as if the file were missing.
info, err := client.StatWithProps(rel, []string{"lockdiscovery", "getetag"})
if err != nil {
return nil, err
}
return &provider.Lock{LockId: token, Type: provider.LockType_LOCK_TYPE_EXCL}, nil
props, ok := info.Sys().(gowebdav.Props)
if !ok {
return nil, errtypes.InternalError("ocm: unexpected stat result for " + ref.GetPath())
}
lock := extractLock(props)
if lock == nil {
// Callers distinguish "locked" from "not locked" by testing the returned
// lock against nil, so a lock must never be invented here.
return nil, errtypes.NotFound("no lock found")
}
return lock, nil
}
func (d *driver) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error {
@@ -659,3 +731,11 @@ func (d *driver) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSto
func (d *driver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
return nil, errtypes.NotSupported("operation not supported")
}
func (d *driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (d *driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
+43 -3
View File
@@ -35,9 +35,11 @@ import (
"strings"
"github.com/google/uuid"
"github.com/studio-b12/gowebdav"
tusd "github.com/tus/tusd/v2/pkg/handler"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
ocmpb "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/owncloud/reva/v2/pkg/appctx"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
@@ -76,12 +78,50 @@ func (d *driver) InitiateUpload(ctx context.Context, ref *provider.Reference, up
}, nil
}
// MarkProcessing is a no-op: the remote instance owns the file, so there is no
// local node to flag while postprocessing runs.
func (d *driver) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error {
return errtypes.NotSupported("op not supported")
return nil
}
func (d *driver) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("op not supported")
// CommitUpload streams the staged bytes to the remote instance over WebDAV.
func (d *driver) CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source storage.UploadSource) error {
client, _, rel, err := d.serviceWebdavClient(ctx, ref)
if err != nil {
return err
}
client.SetInterceptor(func(method string, rq *http.Request) {
// Set the content length on the request struct directly instead of the header.
// The content-length header gets reset by the golang http library before
// sending out the request, resulting in chunked encoding to be used which
// breaks the quota checks in ocdav.
if method == "PUT" {
rq.ContentLength = source.Length
}
})
lockToken, _ := ctxpkg.ContextGetLockID(ctx)
return client.WriteStream(rel, source.Body, 0, lockToken)
}
// serviceWebdavClient builds a webdav client for the upload finish path. That path
// runs under tusd, whose context carries no request auth token, so it authenticates
// as the service account and resolves the share on behalf of the upload's executant.
func (d *driver) serviceWebdavClient(ctx context.Context, ref *provider.Reference) (*gowebdav.Client, *ocmpb.ReceivedShare, string, error) {
gwc, err := d.gateway.Next()
if err != nil {
return nil, nil, "", err
}
serviceUserCtx, err := utils.GetServiceUserContext(d.c.ServiceAccountID, gwc, d.c.ServiceAccountSecret)
if err != nil {
return nil, nil, "", err
}
executant, ok := ctxpkg.ContextGetUser(ctx)
if !ok {
return nil, nil, "", errtypes.BadRequest("ocm: no executant in context")
}
return d.webdavClient(serviceUserCtx, executant.GetId(), ref)
}
func (d *driver) Upload(ctx context.Context, req storage.UploadRequest, _ storage.UploadFinishedFunc) (*provider.ResourceInfo, error) {
+5 -1
View File
@@ -28,12 +28,16 @@ import (
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/storage"
pkgupload "github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
// DataTX provides an abstraction around various data transfer protocols.
//
// Uploads go through the coordinator so the finish path is the same for every
// driver; the driver itself is still needed for downloads.
type DataTX interface {
Handler(fs storage.FS) (http.Handler, error)
Handler(coord pkgupload.Coordinator, driver storage.FS) (http.Handler, error)
}
// EmitFileUploadedEvent is a helper function which publishes a FileUploaded event
@@ -40,6 +40,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
pkgupload "github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -78,7 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord pkgupload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("path", r.URL.Path).Logger()
r = r.WithContext(appctx.WithLogger(r.Context(), &sublog))
@@ -92,7 +93,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, "")
download.GetOrHeadFile(w, r, driver, "")
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -114,7 +115,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
ctx = ctxpkg.ContextSetLockID(ctx, lockID)
}
info, err := fs.Upload(ctx, storage.UploadRequest{
info, err := coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
@@ -42,6 +42,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
pkgupload "github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -80,7 +81,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord pkgupload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var spaceID string
spaceID, r.URL.Path = router.ShiftPath(r.URL.Path)
@@ -97,7 +98,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, spaceID)
download.GetOrHeadFile(w, r, driver, spaceID)
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -117,7 +118,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
Path: fn,
}
var info *provider.ResourceInfo
info, err = fs.Upload(ctx, storage.UploadRequest{
info, err = coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
+42 -45
View File
@@ -33,13 +33,13 @@ import (
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/manager/registry"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storagespace"
pkgupload "github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -87,20 +87,15 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
composable, ok := fs.(storage.ComposableFS)
if !ok {
return nil, errtypes.NotSupported("file system does not support the tus protocol")
}
func (m *manager) Handler(coord pkgupload.Coordinator, driver storage.FS) (http.Handler, error) {
// A storage backend for tusd may consist of multiple different parts which
// handle upload creation, locking, termination and so on. The composer is a
// place where all those separated pieces are joined together. In this example
// we only use the file store but you may plug in multiple.
// place where all those separated pieces are joined together.
composer := tusd.NewStoreComposer()
// let the composable storage tell tus which extensions it supports
composable.UseIn(composer)
// The coordinator is the tus data store for every driver, so finishing an
// upload always ends in driver.CommitUpload.
coord.UseIn(composer)
config := tusd.Config{
StoreComposer: composer,
@@ -130,33 +125,32 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return nil, err
}
if usl, ok := fs.(storage.UploadSessionLister); ok {
// We can currently only send updates if the fs is decomposedfs as we read very specific keys from the storage map of the tus info
go func() {
for {
ev := <-handler.CompleteUploads
// We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files
// so we create a Progress instance here that is used to read the correct properties
ups, err := usl.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
} else {
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
// The coordinator owns the sessions for every driver, so this no longer
// depends on the driver being decomposedfs.
go func() {
for {
ev := <-handler.CompleteUploads
// We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files
// so we create a Progress instance here that is used to read the correct properties
ups, err := coord.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
continue
}
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
}()
}
}
}()
h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("uploadid", r.URL.Path).Logger()
@@ -174,7 +168,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PostFile(w, r)
case "HEAD":
handler.HeadFile(w, r)
@@ -184,7 +178,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PatchFile(w, r)
case "DELETE":
handler.DelFile(w, r)
@@ -205,15 +199,10 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return h, nil
}
func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
func setHeaders(coord pkgupload.Coordinator, w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := path.Base(r.URL.Path)
datastore, ok := fs.(tusd.DataStore)
if !ok {
appctx.GetLogger(ctx).Error().Interface("fs", fs).Msg("storage is not a tus datastore")
return
}
upload, err := datastore.GetUpload(ctx, id)
upload, err := coord.GetUpload(ctx, id)
if err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("could not get upload from storage")
return
@@ -227,6 +216,14 @@ func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
if expires != "" {
w.Header().Set(net.HeaderTusUploadExpires, expires)
}
// These headers are written before the upload is finished. For a new file the
// coordinator has only minted a placeholder node id at initiate; the real one
// arrives from TouchFile at commit. Announcing the placeholder makes callers
// stat an id that does not exist, so leave the header off and let them resolve
// the file by path instead.
if info.Storage["NodeExists"] != "true" {
return
}
resourceid := &provider.ResourceId{
StorageId: info.MetaData["providerID"],
SpaceId: info.Storage["SpaceRoot"],
@@ -275,6 +275,9 @@ func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action s
case errtypes.Aborted:
log.Debug().Err(err).Str("action", action).Msg("etags do not match")
w.WriteHeader(http.StatusPreconditionFailed)
case errtypes.IsResourceProcessing, errtypes.IsTooEarly:
log.Debug().Err(err).Str("action", action).Msg("resource is processing")
w.WriteHeader(http.StatusTooEarly)
default:
log.Error().Err(err).Str("action", action).Msg("unexpected error")
w.WriteHeader(http.StatusInternalServerError)
@@ -100,7 +100,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer unlock()
if _, ok := c.ReceivedSpaces.Load(userID); !ok {
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return err
}
@@ -110,7 +110,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -125,56 +125,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -187,7 +143,7 @@ func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*Stat
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -206,11 +162,11 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Add")
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Remove")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -224,56 +180,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -281,13 +193,14 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
// List returns a list of received shares for a given user
// The return list is guaranteed to be thread-safe
func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, error) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
unlock := c.lockUser(userID)
span.End()
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "List")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
unlock := c.lockUser(userID)
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -310,8 +223,71 @@ func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, err
return spaces, nil
}
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
func isSyncTransient(err error) bool {
_, isTooEarly := err.(errtypes.IsTooEarly)
_, isInternal := err.(errtypes.IsInternalError)
return isTooEarly || isInternal
}
func (c *Cache) retryPersist(ctx context.Context, userID, spaceID string, persistFunc func() error) error {
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
return nil
case errtypes.Aborted:
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: Aborted (etag changed), retrying")
case errtypes.PreconditionFailed:
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: PreconditionFailed (etag changed), retrying")
case errtypes.AlreadyExists:
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: AlreadyExists (file created concurrently), retrying")
case errtypes.TooEarly:
// storage-system has an upload in progress for this node; wait for it to finish
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: TooEarly (upload in progress), retrying")
default:
log.Error().Int("attempt", attempt).Err(err).Msg("persisting received share failed, giving up")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if serr := c.syncIfStale(ctx, userID); serr != nil {
if !isSyncTransient(serr) {
log.Error().Int("attempt", attempt).Err(serr).Msg("lost update: re-read failed, aborting")
return serr
}
log.Warn().Int("attempt", attempt).Err(serr).Msg("lost update: re-read before retry")
}
}
return err
}
// syncIfStale pulls the authoritative state from storage when the local replica is stale; caller must hold the user lock.
func (c *Cache) syncIfStale(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "SyncIfStale")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
@@ -340,8 +316,12 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
span.SetStatus(codes.Ok, "")
return nil
default:
span.SetStatus(codes.Error, fmt.Sprintf("Failed to download the received share: %s", err.Error()))
log.Error().Err(err).Msg("Failed to download the received share")
span.SetStatus(codes.Error, err.Error())
if isSyncTransient(err) {
log.Warn().Err(err).Msg("lost update: re-read transient error")
} else {
log.Error().Err(err).Msg("lost update: re-read failed")
}
return err
}
@@ -365,6 +345,9 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
log := appctx.GetLogger(ctx)
log.Debug().Str("user", userID).Msg("receivedsharecache.persist.start")
rss, ok := c.ReceivedSpaces.Load(userID)
if !ok {
span.SetStatus(codes.Ok, "no received shares")
@@ -395,6 +378,7 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
ur.IfNoneMatch = []string{"*"}
}
log.Debug().Str("user", userID).Str("path", jsonPath).Str("etag", ur.IfMatchEtag).Msg("receivedsharecache.persist.upload")
res, err := c.storage.Upload(ctx, ur)
if err != nil {
span.RecordError(err)
@@ -403,6 +387,7 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
}
rss.etag = res.Etag
log.Debug().Str("user", userID).Str("etag", res.Etag).Msg("receivedsharecache.persist.done")
span.SetStatus(codes.Ok, "")
return nil
}
+10 -2
View File
@@ -151,8 +151,16 @@ func (fs *cephfs) MarkProcessing(ctx context.Context, ref *provider.Reference, p
return errtypes.NotSupported("op not supported")
}
func (fs *cephfs) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("op not supported")
func (fs *cephfs) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
return errtypes.NotSupported("op not supported")
}
func (fs *cephfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *cephfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
// UseIn tells the tus upload middleware which extensions it supports.
+10 -2
View File
@@ -90,8 +90,16 @@ func (fs *hellofs) MarkProcessing(ctx context.Context, ref *provider.Reference,
}
// CommitUpload writes the staged bytes from source to the resource at ref.
func (fs *hellofs) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("hellofs: commit upload not supported")
func (fs *hellofs) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
return errtypes.NotSupported("hellofs: commit upload not supported")
}
func (fs *hellofs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *hellofs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
// grants
+10 -2
View File
@@ -271,8 +271,16 @@ func (d *Driver) MarkProcessing(_ context.Context, _ *provider.Reference, _ bool
return errtypes.NotSupported("kiteworks: read-only driver")
}
func (d *Driver) CommitUpload(_ context.Context, _ *provider.Reference, _ storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("kiteworks: read-only driver")
func (d *Driver) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
return errtypes.NotSupported("kiteworks: read-only driver")
}
func (d *Driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (d *Driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
func (d *Driver) RestoreRevision(_ context.Context, _ *provider.Reference, _ string) (*storage.RestoreRevisionResult, error) {
+53 -8
View File
@@ -21,7 +21,6 @@ package nextcloud
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
@@ -274,7 +273,33 @@ func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference)
// TouchFile as defined in the storage.FS interface
func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
return nil, fmt.Errorf("unimplemented: TouchFile")
type paramsObj struct {
Ref *provider.Reference `json:"ref"`
MarkProcessing bool `json:"markprocessing"`
MTime string `json:"mtime"`
}
bodyStr, err := json.Marshal(&paramsObj{Ref: ref, MarkProcessing: markprocessing, MTime: mtime})
if err != nil {
return nil, err
}
log := appctx.GetLogger(ctx)
log.Info().Msgf("TouchFile %s", bodyStr)
if _, _, err := nc.do(ctx, Action{"TouchFile", string(bodyStr)}); err != nil {
return nil, err
}
// The upload coordinator needs the id of the node that was just created, and
// the touch call itself answers with an empty body, so read it back.
md, err := nc.GetMD(ctx, ref, []string{}, []string{})
if err != nil {
return nil, err
}
return &storage.TouchFileResult{
ResourceID: md.GetId(),
SpaceID: md.GetId().GetSpaceId(),
SpaceOwner: md.GetOwner(),
}, nil
}
// Delete as defined in the storage.FS interface
@@ -409,14 +434,34 @@ func (nc *StorageDriver) InitiateUpload(ctx context.Context, ref *provider.Refer
return respMap, err
}
// MarkProcessing as defined in the storage.FS interface
func (nc *StorageDriver) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error {
return errtypes.NotSupported("nextcloud: mark processing not supported")
// MarkProcessing as defined in the storage.FS interface.
//
// The flag advertises an upload that has been announced but not yet committed, so
// that a stat of the file can say so. Nextcloud owns its own metadata and has
// nowhere to record it, and it does not postprocess uploads, so there is no window
// to report: this is a no-op rather than an error, which would fail the upload.
func (nc *StorageDriver) MarkProcessing(_ context.Context, _ *provider.Reference, _ bool, _ string) error {
return nil
}
// CommitUpload as defined in the storage.FS interface
func (nc *StorageDriver) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("nextcloud: commit upload not supported")
// CommitUpload as defined in the storage.FS interface.
//
// The caller owns source.Body and closes it, so this must not.
func (nc *StorageDriver) CommitUpload(ctx context.Context, ref *provider.Reference, _ string, source storage.UploadSource) error {
if source.Body == nil {
return errtypes.BadRequest("nextcloud: source body is nil")
}
// The remote records the scan verdict itself if it scans at all, so
// source.ScanResult/ScanDate have nowhere to go here.
return nc.doUpload(ctx, ref.GetPath(), source.Body)
}
func (nc *StorageDriver) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (nc *StorageDriver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
// Upload as defined in the storage.FS interface
@@ -25,6 +25,7 @@ import (
"net"
"net/http"
"net/http/httptest"
"regexp"
"strings"
)
@@ -52,6 +53,11 @@ const serverStateMetadata = "METADATA"
var serverState = serverStateEmpty
// TouchFile carries the wall-clock mtime the upload was initiated with, so the
// request body differs on every run. Responses are keyed on the exact body, so
// the value is folded to a placeholder before lookup.
var mtimeRe = regexp.MustCompile(`"mtime":"[^"]*"`)
var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/AddGrant {"ref":{"path":"/subdir"},"g":{"grantee":{"type":1,"Id":{"UserId":{"opaque_id":"4c510ada-c86b-4815-8820-42cdf82c3d51"}}},"permissions":{"delete":true,"initiate_file_download":true,"move":true,"stat":true}}} EMPTY`: {200, ``, serverStateGrantAdded},
@@ -111,7 +117,20 @@ var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetPathByID {"storage_id":"00000000-0000-0000-0000-000000000000","opaque_id":"fileid-/some/path"} EMPTY`: {200, "/subdir", serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
// Initiating an upload now runs through the upload coordinator, which stats the
// target, checks the quota and stats the parent before it reaches the driver.
// The driver used to be called straight away, so none of these had an entry.
// They keep whichever state they matched: this mock selects responses by server
// state, and clearing it would strand the requests that follow.
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":[]} EMPTY`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetQuota EMPTY`: {200, `{"totalBytes":456,"usedBytes":123}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":2,"id":{"opaque_id":"fileid-/"},"checksum":{},"etag":"deadbeef","mime_type":"httpd/unix-directory","mtime":{"seconds":1234567890},"path":"/","permission_set":{"initiate_file_upload":true,"stat":true},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
// A zero-length upload has no bytes to append, so it finishes inside
// InitiateUpload: the coordinator creates the node and stats it back for the id
// the touch minted.
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/TouchFile {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"markprocessing":false,"mtime":"MTIME"} EMPTY`: {200, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/file"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/file","permission_set":{"initiate_file_upload":true,"stat":true},"size":0,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"path":"/file"},"uploadLength":0,"metadata":{"providerID":""}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":1,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":2,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
@@ -194,15 +213,16 @@ func GetNextcloudServerMock(called *[]string) http.Handler {
if err != nil {
panic("Error reading response into buffer")
}
var key = fmt.Sprintf("%s %s %s", r.Method, r.URL, buf.String())
body := mtimeRe.ReplaceAllString(buf.String(), `"mtime":"MTIME"`)
var key = fmt.Sprintf("%s %s %s", r.Method, r.URL, body)
*called = append(*called, key)
response := responses[key]
if (response == Response{}) {
key = fmt.Sprintf("%s %s %s %s", r.Method, r.URL, buf.String(), serverState)
key = fmt.Sprintf("%s %s %s %s", r.Method, r.URL, body, serverState)
response = responses[key]
}
if (response == Response{}) {
fmt.Printf("%s %s %s %s\n", r.Method, r.URL, buf.String(), serverState)
fmt.Printf("%s %s %s %s\n", r.Method, r.URL, body, serverState)
response = Response{500, fmt.Sprintf("response not defined! %s", key), serverStateEmpty}
}
serverState = responses[key].newServerState
+10 -2
View File
@@ -173,8 +173,16 @@ func (fs *owncloudsqlfs) MarkProcessing(ctx context.Context, ref *provider.Refer
return errtypes.NotSupported("op not supported")
}
func (fs *owncloudsqlfs) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("op not supported")
func (fs *owncloudsqlfs) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
return errtypes.NotSupported("op not supported")
}
func (fs *owncloudsqlfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *owncloudsqlfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
// UseIn tells the tus upload middleware which extensions it supports.
+10 -2
View File
@@ -78,6 +78,14 @@ func (fs *s3FS) MarkProcessing(ctx context.Context, ref *provider.Reference, pro
return errtypes.NotSupported("op not supported")
}
func (fs *s3FS) CommitUpload(ctx context.Context, ref *provider.Reference, source storage.UploadSource) (*provider.ResourceInfo, error) {
return nil, errtypes.NotSupported("op not supported")
func (fs *s3FS) CommitUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.UploadSource) error {
return errtypes.NotSupported("op not supported")
}
func (fs *s3FS) PrepareUpload(_ context.Context, _ *provider.Reference, _ string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *s3FS) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
return nil
}
+14 -2
View File
@@ -364,8 +364,11 @@ func (r *registry) findProvidersForFilter(ctx context.Context, filters []*provid
currentUser := ctxpkg.ContextMustGetUser(ctx)
providerInfos := []*registrypb.ProviderInfo{}
for address, provider := range r.c.Providers {
// skip mismatching storageproviders
if storageId != "" && storageId != provider.ProviderID {
// skip mismatching storageproviders. The shares provider hosts the
// mountpoints of vault shares (they grant into the vault provider), so it
// must still be queried when the vault storage id is requested.
if storageId != "" && storageId != provider.ProviderID &&
!(storageId == utils.VaultStorageProviderID && provider.ProviderID == utils.ShareStorageProviderID) {
continue
}
// when a specific space type is requested we may skip this provider altogether if it is not configured for that type
@@ -404,6 +407,15 @@ func (r *registry) findProvidersForFilter(ctx context.Context, filters []*provid
if storageId == "" && provider.ProviderID == utils.VaultStorageProviderID {
continue
}
// Shares of vault resources are mountpoints hosted on the shares
// provider that grant into the vault provider. Segregate them so
// they only appear in the matching (vault / non-vault) drive list.
if provider.ProviderID == utils.ShareStorageProviderID && space.SpaceType == "mountpoint" {
grantsIntoVault := utils.ReadPlainFromOpaque(space.Opaque, "grantStorageID") == utils.VaultStorageProviderID
if grantsIntoVault != (storageId == utils.VaultStorageProviderID) {
continue
}
}
spacePath, err = sc.SpacePath(currentUser, space)
if err != nil {
appctx.GetLogger(ctx).Error().Err(err).Interface("provider", provider).Interface("space", space).Msg("failed to execute template, continuing")
+45 -13
View File
@@ -22,6 +22,7 @@ import (
"context"
"io"
"net/url"
"time"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
@@ -68,6 +69,27 @@ type UnlockResult struct {
SpaceID string
}
type UploadChecksums struct {
SHA1 []byte
MD5 []byte
Adler32 []byte
}
type UploadInfo struct {
NodeExisted bool // true when the target node existed before the upload started
Size int64
MTime time.Time
Checksums UploadChecksums
IfMatch string
IfNoneMatch string
IfUnmodifiedSince time.Time
}
type PrepareUploadResult struct {
VersionCreated bool
SizeDiff int64
}
// FS is the interface to implement access to the storage.
type FS interface {
// Minimal set for a readonly storage driver
@@ -117,7 +139,20 @@ type FS interface {
// MarkProcessing toggles a processing flag on the resource.
MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error
// CommitUpload writes the staged bytes from source to the resource at ref.
CommitUpload(ctx context.Context, ref *provider.Reference, source UploadSource) (*provider.ResourceInfo, error)
// Caller owns source.Body and must close it after CommitUpload returns.
CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source UploadSource) error
// PrepareUpload is called after all bytes are received and before postprocessing begins.
// Implementations may lock the target node, snapshot the previous version, write new metadata,
// and propagate size changes. Drivers that do not require any of these steps may return immediately.
PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info UploadInfo) (*PrepareUploadResult, error)
// RollbackUpload reverts node state after a failed or aborted postprocessing run.
// It is the inverse of PrepareUpload: restores previous metadata and reverts the optimistic
// size propagation. The caller (coordinator) is responsible for unmarking the processing flag
// and deleting the upload session files. Drivers that performed no work in PrepareUpload may return nil.
// nodeExisted indicates whether the target node had a prior version. When it is false the
// upload itself created the node, and the driver must remove it outright rather than move it
// to the trash: the file never became visible, so it must not be recoverable.
RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, nodeExisted bool, sizeDiff int64) error
// Revisions
@@ -211,20 +246,17 @@ type DeleteStorageSpaceResult struct {
FinalMembers map[string]provider.ResourcePermissions
}
// UploadChecksums holds pre-computed checksums for a CommitUpload call.
// All three must be provided; the driver stores them as xattrs without recomputing.
type UploadChecksums struct {
SHA1 []byte
MD5 []byte
Adler32 []byte
}
// UploadSource carries the staged bytes for a CommitUpload call.
type UploadSource struct {
Body io.ReadCloser
Length int64
Metadata map[string]string
Checksums UploadChecksums
Body io.ReadCloser
Length int64
// ScanResult and ScanDate carry the antivirus verdict the bytes were cleared
// under, for drivers that expose scan state on the resource. ScanDate is zero
// when the upload was not scanned; ScanResult is empty for a clean scan, so it
// cannot be used to tell "clean" from "not scanned".
ScanResult string
ScanDate time.Time
}
// UnscopeFunc is a function that unscopes a user
@@ -201,6 +201,46 @@ func (c *ChunkHandler) saveChunk(path string, r io.ReadCloser) (bool, string, er
return true, assembledFileName, nil
}
// Assemble saves an intermediate chunk and, once all chunks have arrived,
// assembles them into a single temp file. Returns (reader, size, true, nil)
// when the transfer is complete. Returns (nil, 0, false, nil) when more
// chunks are still expected (partial transfer — caller should return PartialContent).
//
// The returned reader removes the temp file on Close.
func (c *ChunkHandler) Assemble(chunkName string, body io.ReadCloser) (io.ReadCloser, int64, bool, error) {
origPath, assembledPath, err := c.WriteChunk(chunkName, body)
if err != nil {
return nil, 0, false, err
}
if origPath == "" {
return nil, 0, false, nil // partial
}
f, err := os.Open(assembledPath)
if err != nil {
_ = os.RemoveAll(assembledPath)
return nil, 0, false, err
}
fi, err := f.Stat()
if err != nil {
_ = f.Close()
_ = os.RemoveAll(assembledPath)
return nil, 0, false, err
}
return &assembledFile{File: f, path: assembledPath}, fi.Size(), true, nil
}
// assembledFile wraps an *os.File and removes the temp file on Close.
type assembledFile struct {
*os.File
path string
}
func (a *assembledFile) Close() error {
err := a.File.Close()
_ = os.RemoveAll(a.path)
return err
}
// WriteChunk saves an intermediate chunk temporarily and assembles all chunks
// once the final one is received.
func (c *ChunkHandler) WriteChunk(fn string, r io.ReadCloser) (string, string, error) {
@@ -28,9 +28,7 @@ import (
"path/filepath"
"strconv"
"strings"
"time"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/jellydator/ttlcache/v2"
@@ -49,7 +47,6 @@ import (
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/logger"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/aspects"
@@ -81,11 +78,11 @@ const (
var (
tracer trace.Tracer
// The upload-related postprocessing events are consumed by the upload
// coordinator (pkg/upload), which owns the upload lifecycle for every driver.
// RevertRevision is not part of that lifecycle: the storage-users CLI emits it
// to undo a revision, and reverting one needs the driver's node internals.
_registeredEvents = []events.Unmarshaller{
events.PostprocessingFinished{},
events.PostprocessingStepFinished{},
events.RestartPostprocessing{},
events.CleanUpload{},
events.RevertRevision{},
}
)
@@ -234,6 +231,13 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
aspects.UserMapper = &usermapper.NullMapper{}
}
// Callers may disable versioning through either the options or the aspects: the
// posix driver builds its own aspects and only sets it there. Fold it into the
// options so code reading o.DisableVersioning sees it too.
if aspects.DisableVersioning {
o.DisableVersioning = true
}
fs := &Decomposedfs{
tp: aspects.Tree,
lu: aspects.Lookup,
@@ -254,35 +258,39 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
return nil, err
}
// Gated on AsyncFileUploads only because that is the flag that has always
// enabled this subscription; reverting a revision is otherwise unrelated to
// async uploads. Widening it would start a consumer in deployments that never
// had one.
if o.AsyncFileUploads {
if fs.stream == nil {
log.Error().Msg("need event stream for async file processing")
return nil, errors.New("need nats for async file processing")
}
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup, _registeredEvents...)
// A group name is also the JetStream durable consumer name, and members of one
// group share messages rather than each getting a copy. This must therefore not
// share the coordinator's group: an upload event delivered here would be
// dropped by the type filter above and never reach the coordinator.
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup+"-revisions", _registeredEvents...)
if err != nil {
return nil, err
}
if o.Events.NumConsumers <= 0 {
o.Events.NumConsumers = 1
}
for i := 0; i < o.Events.NumConsumers; i++ {
go fs.Postprocessing(ch)
}
// One consumer is enough: revisions are reverted by a maintenance command,
// not by upload traffic.
go fs.ConsumeRevisionEvents(ch)
}
return fs, nil
}
// Postprocessing starts the postprocessing result collector
func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
// ConsumeRevisionEvents handles revision events until ch is closed. Upload
// postprocessing lives in the upload coordinator; this only reverts revisions on
// behalf of the storage-users CLI, which needs the driver's node internals.
func (fs *Decomposedfs) ConsumeRevisionEvents(ch <-chan events.Event) {
log := logger.New()
for event := range ch {
evCtx := context.Background()
fs.processEvent(evCtx, event, log)
fs.processEvent(context.Background(), event, log)
}
}
@@ -292,175 +300,6 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
defer span.End()
switch ev := event.Event.(type) {
case events.PostprocessingFinished:
sublog := log.With().Str("event", "PostprocessingFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
ctx = session.Context(ctx)
n, err := session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read node")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
if !n.Exists {
sublog.Debug().Msg("node no longer exists")
session.Cleanup(false, true, true, false)
return
}
var (
failed bool
revertNodeMetadata bool
keepUpload bool
)
unmarkPostprocessing := true
switch ev.Outcome {
default:
sublog.Error().Str("outcome", string(ev.Outcome)).Msg("unknown postprocessing outcome - aborting")
fallthrough
case events.PPOutcomeAbort:
failed = true
revertNodeMetadata = true
keepUpload = true
metrics.UploadSessionsAborted.Inc()
case events.PPOutcomeContinue:
if err := session.Finalize(ctx); err != nil {
sublog.Error().Err(err).Msg("could not finalize upload")
failed = true
revertNodeMetadata = false
keepUpload = true
// keep postprocessing status so the upload is not deleted during housekeeping
unmarkPostprocessing = false
} else {
metrics.UploadSessionsFinalized.Inc()
}
case events.PPOutcomeDelete:
failed = true
revertNodeMetadata = true
metrics.UploadSessionsDeleted.Inc()
}
getParent := func() *node.Node {
p, err := n.Parent(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read parent")
return nil
}
return p
}
now := time.Now()
if failed {
// if no other upload session is in progress (processing id != session id) or has finished (processing id == "")
latestSession, err := n.ProcessingID(ctx)
if err != nil {
sublog.Error().Err(err).Msg("reading node for session failed")
}
if latestSession == session.ID() {
// propagate reverted sizeDiff after failed postprocessing
if err := fs.tp.Propagate(ctx, n, -session.SizeDiff()); err != nil {
sublog.Error().Err(err).Msg("could not propagate tree size change")
}
}
} else if p := getParent(); p != nil {
// update parent tmtime to propagate etag change after successful postprocessing
_ = p.SetTMTime(ctx, &now)
if err := fs.tp.Propagate(ctx, p, 0); err != nil {
sublog.Error().Err(err).Msg("could not propagate etag change")
}
}
session.Cleanup(revertNodeMetadata, !keepUpload, !keepUpload, unmarkPostprocessing)
var isVersion bool
if session.NodeExists() {
info, err := session.GetInfo(ctx)
if err == nil && info.MetaData["versionsPath"] != "" {
isVersion = true
}
}
if err := events.Publish(
ctx,
fs.stream,
events.UploadReady{
UploadID: ev.UploadID,
Failed: failed,
ExecutingUser: ev.ExecutingUser,
Filename: ev.Filename,
FileRef: &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.SpaceID(),
},
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
},
ResourceID: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.NodeID(),
},
Timestamp: utils.TimeToTS(now),
SpaceOwner: n.SpaceOwnerOrManager(ctx),
IsVersion: isVersion,
ImpersonatingUser: ev.ImpersonatingUser,
},
); err != nil {
sublog.Error().Err(err).Msg("Failed to publish UploadReady event")
}
case events.RestartPostprocessing:
sublog := log.With().Str("event", "RestartPostprocessing").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err := session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read node")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
s, err := session.URL(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not create url")
return
}
metrics.UploadSessionsRestarted.Inc()
// restart postprocessing
if err := events.Publish(ctx, fs.stream, events.BytesReceived{
UploadID: session.ID(),
URL: s,
SpaceOwner: n.SpaceOwnerOrManager(ctx),
ExecutingUser: &user.User{Id: &user.UserId{OpaqueId: "postprocessing-restart"}}, // send nil instead?
ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID},
Filename: session.Filename(),
Filesize: uint64(session.Size()),
}); err != nil {
sublog.Error().Err(err).Msg("Failed to publish BytesReceived event")
}
case events.CleanUpload:
sublog := log.With().Str("event", "CleanUpload").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
session.Cleanup(true, !ev.KeepUpload, !ev.KeepUpload, true)
case events.RevertRevision:
sublog := log.With().Str("event", "RevertRevision").Interface("nodeid", ev.ResourceID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
@@ -473,136 +312,10 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
return
}
if err := n.RevertCurrentRevision(ctx); err != nil {
if err := n.RevertCurrentRevision(ctx, true); err != nil {
sublog.Error().Err(err).Msg("Failed to revert revision")
return
}
case events.PostprocessingStepFinished:
sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
if ev.FinishedStep != events.PPStepAntivirus {
// atm we are only interested in antivirus results
return
}
res := ev.Result.(events.VirusscanResult)
if res.ErrorMsg != "" {
// scan failed somehow
// Should we handle this here?
return
}
sublog = log.With().Str("scan_description", res.Description).Bool("infected", res.Infected).Logger()
var n *node.Node
switch ev.UploadID {
case "":
// uploadid is empty -> this was an on-demand scan
/* ON DEMAND SCANNING NOT SUPPORTED ATM
ctx := ctxpkg.ContextSetUser(context.Background(), ev.ExecutingUser)
ref := &provider.Reference{ResourceId: ev.ResourceID}
no, err := fs.lu.NodeFromResource(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to get node after scan")
continue
}
n = no
if ev.Outcome == events.PPOutcomeDelete {
// antivir wants us to delete the file. We must obey and need to
// check if there a previous versions existing
revs, err := fs.ListRevisions(ctx, ref)
if len(revs) == 0 {
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to list revisions. Fallback to delete file")
}
// no versions -> trash file
err := fs.Delete(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to delete infected resource")
continue
}
// now purge it from the recycle bin
if err := fs.PurgeRecycleItem(ctx, &provider.Reference{ResourceId: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}}, n.ID, "/"); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to purge infected resource from trash")
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
// we have versions - find the newest
versions := make(map[uint64]string) // remember all versions - we need them later
var nv uint64
for _, v := range revs {
versions[v.Mtime] = v.Key
if v.Mtime > nv {
nv = v.Mtime
}
}
// restore newest version
if err := fs.RestoreRevision(ctx, ref, versions[nv]); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", versions[nv]).Msg("Failed to restore revision")
continue
}
// now find infected version
revs, err = fs.ListRevisions(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Error listing revisions after restore")
}
for _, v := range revs {
// we looking for a version that was previously not there
if _, ok := versions[v.Mtime]; ok {
continue
}
if err := fs.DeleteRevision(ctx, ref, v.Key); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", v.Key).Msg("Failed to delete revision")
}
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
*/
default:
// uploadid is not empty -> this is an async upload
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err = session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get node after scan")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
session.SetScanData(res.Description, res.Scandate)
if err := session.Persist(ctx); err != nil {
sublog.Error().Err(err).Msg("Failed to persist scan results")
}
}
if err := n.SetScanData(ctx, res.Description, res.Scandate); err != nil {
sublog.Error().Err(err).Msg("Failed to set scan results")
return
}
metrics.UploadSessionsScanned.Inc()
default:
log.Error().Interface("event", ev).Msg("Unknown event")
}
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff. Show more