From 3dfae3b9841ab05afa7ac62eddc4e584f86df0ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Wed, 30 Sep 2026 09:59:43 +0200 Subject: [PATCH 01/19] fix(search): honor the gRPC client TLS mode in the index command The index command read OC_GRPC_CLIENT_TLS_MODE with a meaning of its own: "insecure" dialed without TLS, and every other value, including the default and "off", dialed with verified TLS and ignored OC_GRPC_CLIENT_TLS_CACERT. Against the default setup, where the gRPC services run without TLS, it failed unless --insecure was passed, and against services with TLS enabled it only connected when their certificate was trusted by the system roots, never with the generated certificate or a private CA. Map the mode with pool.StringToTLSMode and dial with pool.NewConn, the mapping and dialer the other services' reva clients use: "off" dials without TLS, "insecure" uses TLS without verifying the certificate and "on" verifies it against the configured CA. --insecure still forces a connection without TLS, and then the mode is not read at all. --- services/search/pkg/command/index.go | 24 ++--- services/search/pkg/command/index_test.go | 124 ++++++++++++++++++++++ 2 files changed, 136 insertions(+), 12 deletions(-) create mode 100644 services/search/pkg/command/index_test.go diff --git a/services/search/pkg/command/index.go b/services/search/pkg/command/index.go index c9b27814c1..dfc7eb6cfb 100644 --- a/services/search/pkg/command/index.go +++ b/services/search/pkg/command/index.go @@ -2,7 +2,6 @@ package command import ( "context" - "crypto/tls" "errors" "fmt" "io" @@ -14,11 +13,9 @@ import ( searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/pkg/config" "github.com/opencloud-eu/opencloud/services/search/pkg/config/parser" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/spf13/cobra" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/insecure" ) // Index is the entrypoint for the server command. @@ -45,16 +42,19 @@ func Index(cfg *config.Config) *cobra.Command { return fmt.Errorf("concurrency %d exceeds max allowed %d", concurrencyFlag, cfg.ReindexMaxConcurrency) } - var dialOpts []grpc.DialOption - if cfg.GRPCClientTLS.Mode == "insecure" || insecureFlag { - dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) - } else { - dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ - MinVersion: tls.VersionTLS12, - }))) + tlsMode := pool.TLSOff + if !insecureFlag { + mode, err := pool.StringToTLSMode(cfg.GRPCClientTLS.Mode) + if err != nil { + return err + } + tlsMode = mode } - conn, err := grpc.NewClient(endpointFlag, dialOpts...) + conn, err := pool.NewConn(endpointFlag, + pool.WithTLSMode(tlsMode), + pool.WithTLSCACert(cfg.GRPCClientTLS.CACert), + ) if err != nil { return fmt.Errorf("failed to dial %s: %w", endpointFlag, err) } diff --git a/services/search/pkg/command/index_test.go b/services/search/pkg/command/index_test.go new file mode 100644 index 0000000000..978ebb37b0 --- /dev/null +++ b/services/search/pkg/command/index_test.go @@ -0,0 +1,124 @@ +package command + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "os" + "path/filepath" + "testing" + "time" + + "github.com/opencloud-eu/opencloud/pkg/shared" + searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" + "github.com/opencloud-eu/opencloud/services/search/pkg/config" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" +) + +type fakeSearchProvider struct { + searchsvc.UnimplementedSearchProviderServer +} + +func (fakeSearchProvider) IndexSpace(_ *searchsvc.IndexSpaceRequest, stream grpc.ServerStreamingServer[searchsvc.IndexSpaceResponse]) error { + return stream.Send(&searchsvc.IndexSpaceResponse{SpaceId: "space-1", IndexedSpaces: 1, TotalSpaces: 1}) +} + +// startSearchServer serves a fake search service on a random local port and +// returns its address. +func startSearchServer(t *testing.T, opts ...grpc.ServerOption) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + srv := grpc.NewServer(opts...) + searchsvc.RegisterSearchProviderServer(srv, fakeSearchProvider{}) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// selfSignedCert returns a certificate for 127.0.0.1 and the path of a PEM +// file holding it, to be used as the CA certificate by the client. +func selfSignedCert(t *testing.T) (tls.Certificate, string) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "127.0.0.1"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IsCA: true, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + require.NoError(t, err) + keyDER, err := x509.MarshalECPrivateKey(key) + require.NoError(t, err) + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + cert, err := tls.X509KeyPair(certPEM, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})) + require.NoError(t, err) + caFile := filepath.Join(t.TempDir(), "ca.pem") + require.NoError(t, os.WriteFile(caFile, certPEM, 0o600)) + return cert, caFile +} + +func TestIndexHonorsGRPCClientTLSMode(t *testing.T) { + plain := startSearchServer(t) + cert, caFile := selfSignedCert(t) + withTLS := startSearchServer(t, grpc.Creds(credentials.NewServerTLSFromCert(&cert))) + + tests := []struct { + name string + endpoint string + mode string + caCert string + insecure bool + wantErr bool + errContains string + }{ + {name: "no TLS, mode unset", endpoint: plain}, + {name: "no TLS, mode off", endpoint: plain, mode: "off"}, + {name: "no TLS, --insecure", endpoint: plain, insecure: true}, + {name: "TLS, mode insecure", endpoint: withTLS, mode: "insecure"}, + {name: "TLS, mode on with CA certificate", endpoint: withTLS, mode: "on", caCert: caFile}, + {name: "no TLS, mode insecure", endpoint: plain, mode: "insecure", wantErr: true}, + {name: "TLS, mode off", endpoint: withTLS, mode: "off", wantErr: true}, + {name: "unknown mode", endpoint: plain, mode: "bogus", wantErr: true, errContains: "unknown TLS mode"}, + {name: "unknown mode, --insecure", endpoint: plain, mode: "bogus", insecure: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := &config.Config{ + GRPCClientTLS: &shared.GRPCClientTLS{Mode: tt.mode, CACert: tt.caCert}, + ReindexMaxConcurrency: 3, + } + cmd := Index(cfg) + require.NoError(t, cmd.Flags().Set("all-spaces", "true")) + require.NoError(t, cmd.Flags().Set("endpoint", tt.endpoint)) + if tt.insecure { + require.NoError(t, cmd.Flags().Set("insecure", "true")) + } + + err := cmd.RunE(cmd, nil) + switch { + case tt.errContains != "": + require.ErrorContains(t, err, tt.errContains) + case tt.wantErr: + require.Error(t, err) + default: + require.NoError(t, err) + } + }) + } +} From e44bd467f3dc86cfed9353ac97c7eabe39f88d73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 09:44:27 +0200 Subject: [PATCH 02/19] fix(search): default the index endpoint to the configured gRPC address --endpoint defaulted to a hardcoded 127.0.0.1:9220, so a search service moved with SEARCH_GRPC_ADDR could only be reached by passing the flag. Use the configured address when the flag is not set. --- services/search/pkg/command/index.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/services/search/pkg/command/index.go b/services/search/pkg/command/index.go index dfc7eb6cfb..73f7703f53 100644 --- a/services/search/pkg/command/index.go +++ b/services/search/pkg/command/index.go @@ -42,6 +42,10 @@ func Index(cfg *config.Config) *cobra.Command { return fmt.Errorf("concurrency %d exceeds max allowed %d", concurrencyFlag, cfg.ReindexMaxConcurrency) } + if !cmd.Flags().Changed("endpoint") { + endpointFlag = cfg.GRPC.Addr + } + tlsMode := pool.TLSOff if !insecureFlag { mode, err := pool.StringToTLSMode(cfg.GRPCClientTLS.Mode) @@ -122,8 +126,8 @@ func Index(cfg *config.Config) *cobra.Command { ) indexCmd.Flags().String( "endpoint", - "127.0.0.1:9220", - "the address of the search service gRPC endpoint.", + "", + "the address of the search service gRPC endpoint. Defaults to the service's configured gRPC address (SEARCH_GRPC_ADDR).", ) indexCmd.Flags().Bool( "insecure", From 3e5e5439a340acb9bd2cfd91fa47046c73abe656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 09:44:27 +0200 Subject: [PATCH 03/19] fix(search): stop recommending --insecure for re-indexing With the client TLS mode honored, the default setup no longer needs --insecure, and with TLS enabled for gRPC the flag makes the command fail, since it turns TLS off. Drop it from the README examples and from the two re-index hints the service logs. MIGRATION.md keeps it: its section covers upgrading to 8.0.x, which still needs the flag. --- services/search/README.md | 4 ++-- services/search/pkg/mapping/reconcile.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/search/README.md b/services/search/README.md index d0f650e528..96bdc00c21 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -124,14 +124,14 @@ opencloud search index --space $SPACE_ID It can also be used to re-index all spaces: ```shell -opencloud search index --all-spaces --insecure +opencloud search index --all-spaces ``` Please note that a reindex only picks up new or changed files. Files that have already been indexed are not scanned again, even if the configuration or the whole extractor has been changed. To force a full rescan (re-running the extractor on every file) you need to use the `force-rescan` flag: ```shell -opencloud search index --all-spaces --force-rescan --insecure +opencloud search index --all-spaces --force-rescan ``` ## Metrics diff --git a/services/search/pkg/mapping/reconcile.go b/services/search/pkg/mapping/reconcile.go index 7490998a67..82cc46feb6 100644 --- a/services/search/pkg/mapping/reconcile.go +++ b/services/search/pkg/mapping/reconcile.go @@ -27,7 +27,7 @@ func Reconcile(index string, r SchemaReconciler, logger log.Logger) (Classificat case VerdictAdditive: persisted, err := r.ApplyAdditive() if persisted { - logger.Warn().Strs("fields", classification.NewFields).Str("index", index).Msg("extended the search index mapping with new fields; documents indexed before the upgrade do not contain them and queries on these fields will miss those documents until they are re-indexed; to re-index everything run: opencloud search index --all-spaces --force-rescan --insecure") + logger.Warn().Strs("fields", classification.NewFields).Str("index", index).Msg("extended the search index mapping with new fields; documents indexed before the upgrade do not contain them and queries on these fields will miss those documents until they are re-indexed; to re-index everything run: opencloud search index --all-spaces --force-rescan") } if err != nil { return classification, err @@ -40,5 +40,5 @@ func Reconcile(index string, r SchemaReconciler, logger log.Logger) (Classificat // LogNewIndexCreated logs that a fresh, empty index was created and how to // backfill it. The create path does not run through Reconcile. func LogNewIndexCreated(logger log.Logger, index string) { - logger.Info().Str("index", index).Msg("created a new empty search index; if this OpenCloud instance already held files, they are not in it yet, index them by running: opencloud search index --all-spaces --force-rescan --insecure") + logger.Info().Str("index", index).Msg("created a new empty search index; if this OpenCloud instance already held files, they are not in it yet, index them by running: opencloud search index --all-spaces --force-rescan") } From 828f7fe8f1a22a668ddcb2a69187af01ac476558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 09:44:27 +0200 Subject: [PATCH 04/19] test(search): rewrite the index command test with Ginkgo Run the command against a search service without TLS only: what the command decides is whether to turn TLS off, how the mode maps and which endpoint it dials. What pool.NewConn does with each mode belongs to reva. Also cover the endpoint default. --- .../search/pkg/command/command_suite_test.go | 13 ++ services/search/pkg/command/index_test.go | 153 ++++++------------ 2 files changed, 64 insertions(+), 102 deletions(-) create mode 100644 services/search/pkg/command/command_suite_test.go diff --git a/services/search/pkg/command/command_suite_test.go b/services/search/pkg/command/command_suite_test.go new file mode 100644 index 0000000000..c76f359e41 --- /dev/null +++ b/services/search/pkg/command/command_suite_test.go @@ -0,0 +1,13 @@ +package command_test + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestCommand(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Command Suite") +} diff --git a/services/search/pkg/command/index_test.go b/services/search/pkg/command/index_test.go index 978ebb37b0..4d8fa51fe7 100644 --- a/services/search/pkg/command/index_test.go +++ b/services/search/pkg/command/index_test.go @@ -1,26 +1,16 @@ -package command +package command_test import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" "net" - "os" - "path/filepath" - "testing" - "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "google.golang.org/grpc" "github.com/opencloud-eu/opencloud/pkg/shared" searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" + "github.com/opencloud-eu/opencloud/services/search/pkg/command" "github.com/opencloud-eu/opencloud/services/search/pkg/config" - "github.com/stretchr/testify/require" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" ) type fakeSearchProvider struct { @@ -31,94 +21,53 @@ func (fakeSearchProvider) IndexSpace(_ *searchsvc.IndexSpaceRequest, stream grpc return stream.Send(&searchsvc.IndexSpaceResponse{SpaceId: "space-1", IndexedSpaces: 1, TotalSpaces: 1}) } -// startSearchServer serves a fake search service on a random local port and -// returns its address. -func startSearchServer(t *testing.T, opts ...grpc.ServerOption) string { - t.Helper() - lis, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - srv := grpc.NewServer(opts...) - searchsvc.RegisterSearchProviderServer(srv, fakeSearchProvider{}) - go func() { _ = srv.Serve(lis) }() - t.Cleanup(srv.Stop) - return lis.Addr().String() -} +var _ = Describe("Index", func() { + var addr string -// selfSignedCert returns a certificate for 127.0.0.1 and the path of a PEM -// file holding it, to be used as the CA certificate by the client. -func selfSignedCert(t *testing.T) (tls.Certificate, string) { - t.Helper() - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) - tmpl := &x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{CommonName: "127.0.0.1"}, - IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - IsCA: true, - BasicConstraintsValid: true, + // runIndex runs the index command against a search service without TLS + // that listens on the configured gRPC address. + runIndex := func(mode string, args ...string) error { + cfg := &config.Config{ + GRPC: config.GRPCConfig{Addr: addr}, + GRPCClientTLS: &shared.GRPCClientTLS{Mode: mode}, + ReindexMaxConcurrency: 3, + } + cmd := command.Index(cfg) + Expect(cmd.ParseFlags(append([]string{"--all-spaces"}, args...))).To(Succeed()) + return cmd.RunE(cmd, nil) } - der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) - require.NoError(t, err) - keyDER, err := x509.MarshalECPrivateKey(key) - require.NoError(t, err) - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) - cert, err := tls.X509KeyPair(certPEM, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})) - require.NoError(t, err) - caFile := filepath.Join(t.TempDir(), "ca.pem") - require.NoError(t, os.WriteFile(caFile, certPEM, 0o600)) - return cert, caFile -} -func TestIndexHonorsGRPCClientTLSMode(t *testing.T) { - plain := startSearchServer(t) - cert, caFile := selfSignedCert(t) - withTLS := startSearchServer(t, grpc.Creds(credentials.NewServerTLSFromCert(&cert))) + BeforeEach(func() { + lis, err := net.Listen("tcp", "127.0.0.1:0") + Expect(err).ToNot(HaveOccurred()) + srv := grpc.NewServer() + searchsvc.RegisterSearchProviderServer(srv, fakeSearchProvider{}) + go func() { _ = srv.Serve(lis) }() + DeferCleanup(srv.Stop) + addr = lis.Addr().String() + }) - tests := []struct { - name string - endpoint string - mode string - caCert string - insecure bool - wantErr bool - errContains string - }{ - {name: "no TLS, mode unset", endpoint: plain}, - {name: "no TLS, mode off", endpoint: plain, mode: "off"}, - {name: "no TLS, --insecure", endpoint: plain, insecure: true}, - {name: "TLS, mode insecure", endpoint: withTLS, mode: "insecure"}, - {name: "TLS, mode on with CA certificate", endpoint: withTLS, mode: "on", caCert: caFile}, - {name: "no TLS, mode insecure", endpoint: plain, mode: "insecure", wantErr: true}, - {name: "TLS, mode off", endpoint: withTLS, mode: "off", wantErr: true}, - {name: "unknown mode", endpoint: plain, mode: "bogus", wantErr: true, errContains: "unknown TLS mode"}, - {name: "unknown mode, --insecure", endpoint: plain, mode: "bogus", insecure: true}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cfg := &config.Config{ - GRPCClientTLS: &shared.GRPCClientTLS{Mode: tt.mode, CACert: tt.caCert}, - ReindexMaxConcurrency: 3, - } - cmd := Index(cfg) - require.NoError(t, cmd.Flags().Set("all-spaces", "true")) - require.NoError(t, cmd.Flags().Set("endpoint", tt.endpoint)) - if tt.insecure { - require.NoError(t, cmd.Flags().Set("insecure", "true")) - } + DescribeTable("connects without TLS", + func(mode string, args ...string) { + Expect(runIndex(mode, args...)).To(Succeed()) + }, + Entry("when the mode is unset", ""), + Entry("when the mode is off", "off"), + Entry("when --insecure is passed", "", "--insecure"), + Entry("when --insecure is passed with an unknown mode", "bogus", "--insecure"), + ) - err := cmd.RunE(cmd, nil) - switch { - case tt.errContains != "": - require.ErrorContains(t, err, tt.errContains) - case tt.wantErr: - require.Error(t, err) - default: - require.NoError(t, err) - } - }) - } -} + It("uses TLS when the mode is insecure", func() { + Expect(runIndex("insecure")).To(HaveOccurred()) + }) + + It("rejects an unknown mode", func() { + Expect(runIndex("bogus")).To(MatchError(ContainSubstring("unknown TLS mode"))) + }) + + It("prefers --endpoint over the configured gRPC address", func() { + endpoint := addr + addr = "127.0.0.1:1" + Expect(runIndex("", "--endpoint", endpoint)).To(Succeed()) + }) +}) From f6bd4364287f0f74bb74e16e555857fa5ea195b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 12:37:26 +0200 Subject: [PATCH 05/19] docs(search): cover every 8.x release in the v7 migration [docs-only] The section was titled v7.x.x to v8.0.0 and told everyone to pass --insecure, which only 8.0.0 and 8.0.1 need. Title it v7.x.x to v8.x.x, drop the flag from the commands and say in an IMPORTANT block which releases still need it. --- services/search/MIGRATION.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/services/search/MIGRATION.md b/services/search/MIGRATION.md index 3a026b18c6..12ad80a673 100644 --- a/services/search/MIGRATION.md +++ b/services/search/MIGRATION.md @@ -5,7 +5,12 @@ leaves the old one untouched. The service starts normally, but the new index is empty: search finds nothing until it is filled. The old index stays around until you remove it. -## v7.x.x to v8.0.0 +## v7.x.x to v8.x.x + +> [!IMPORTANT] +> On 8.0.0 and 8.0.1, `opencloud search index` needs `--insecure` in the +> default setup, where the search service runs gRPC without TLS: add it to the +> commands below. Later releases don't need it. ### OpenSearch @@ -13,7 +18,7 @@ Fill the new index by indexing all spaces again: ```shell # the service keeps running while it happens -opencloud search index --all-spaces --insecure +opencloud search index --all-spaces ``` Once the new index is filled, every index but the one with the highest @@ -31,7 +36,7 @@ The new index is a directory next to the old `bleve` one, both in bleve index cannot be copied, index all spaces again: ```shell -opencloud search index --all-spaces --insecure +opencloud search index --all-spaces ``` Once the new index is filled, every directory but the one with the highest From d071dc78ed5655631bfadbf58c01ed1d13689d11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 15:58:10 +0200 Subject: [PATCH 06/19] test(search): pin the TLS failure and declare the plaintext server The insecure-mode spec only asserted an error, so against main it passed on a refused connection to the hardcoded endpoint. Match the TLS handshake error instead. Pass insecure credentials to the test server explicitly, which is what it already did, so the static analysis no longer reports a server without credentials. --- services/search/pkg/command/index_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/search/pkg/command/index_test.go b/services/search/pkg/command/index_test.go index 4d8fa51fe7..f34d3558ba 100644 --- a/services/search/pkg/command/index_test.go +++ b/services/search/pkg/command/index_test.go @@ -6,6 +6,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "github.com/opencloud-eu/opencloud/pkg/shared" searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" @@ -40,7 +41,7 @@ var _ = Describe("Index", func() { BeforeEach(func() { lis, err := net.Listen("tcp", "127.0.0.1:0") Expect(err).ToNot(HaveOccurred()) - srv := grpc.NewServer() + srv := grpc.NewServer(grpc.Creds(insecure.NewCredentials())) searchsvc.RegisterSearchProviderServer(srv, fakeSearchProvider{}) go func() { _ = srv.Serve(lis) }() DeferCleanup(srv.Stop) @@ -58,7 +59,7 @@ var _ = Describe("Index", func() { ) It("uses TLS when the mode is insecure", func() { - Expect(runIndex("insecure")).To(HaveOccurred()) + Expect(runIndex("insecure")).To(MatchError(ContainSubstring("first record does not look like a TLS handshake"))) }) It("rejects an unknown mode", func() { From 6211e31b5daa2e74b8b6cef46ca700dec772a041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 15:58:20 +0200 Subject: [PATCH 07/19] refactor(search): rename the dialed endpoint and group the reva import After the fallback the variable holds the configured address rather than the flag, and the reva import belongs with the third-party ones, as in server.go. The flag help also says that with mode on the server certificate must be valid for that address. --- services/search/pkg/command/index.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/search/pkg/command/index.go b/services/search/pkg/command/index.go index 73f7703f53..0da05850ba 100644 --- a/services/search/pkg/command/index.go +++ b/services/search/pkg/command/index.go @@ -13,8 +13,8 @@ import ( searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0" "github.com/opencloud-eu/opencloud/services/search/pkg/config" "github.com/opencloud-eu/opencloud/services/search/pkg/config/parser" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/spf13/cobra" ) @@ -31,7 +31,7 @@ func Index(cfg *config.Config) *cobra.Command { allSpacesFlag, _ := cmd.Flags().GetBool("all-spaces") spaceFlag, _ := cmd.Flags().GetString("space") forceRescanFlag, _ := cmd.Flags().GetBool("force-rescan") - endpointFlag, _ := cmd.Flags().GetString("endpoint") + endpoint, _ := cmd.Flags().GetString("endpoint") insecureFlag, _ := cmd.Flags().GetBool("insecure") concurrencyFlag, _ := cmd.Flags().GetInt("concurrency") @@ -43,7 +43,7 @@ func Index(cfg *config.Config) *cobra.Command { } if !cmd.Flags().Changed("endpoint") { - endpointFlag = cfg.GRPC.Addr + endpoint = cfg.GRPC.Addr } tlsMode := pool.TLSOff @@ -55,12 +55,12 @@ func Index(cfg *config.Config) *cobra.Command { tlsMode = mode } - conn, err := pool.NewConn(endpointFlag, + conn, err := pool.NewConn(endpoint, pool.WithTLSMode(tlsMode), pool.WithTLSCACert(cfg.GRPCClientTLS.CACert), ) if err != nil { - return fmt.Errorf("failed to dial %s: %w", endpointFlag, err) + return fmt.Errorf("failed to dial %s: %w", endpoint, err) } defer conn.Close() @@ -127,7 +127,7 @@ func Index(cfg *config.Config) *cobra.Command { indexCmd.Flags().String( "endpoint", "", - "the address of the search service gRPC endpoint. Defaults to the service's configured gRPC address (SEARCH_GRPC_ADDR).", + "the address of the search service gRPC endpoint. Defaults to the service's configured gRPC address (SEARCH_GRPC_ADDR). With OC_GRPC_CLIENT_TLS_MODE=on the server certificate must be valid for this address.", ) indexCmd.Flags().Bool( "insecure", From 6a83068be231ed9fdbb822478df08483ca96741a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 15:58:20 +0200 Subject: [PATCH 08/19] docs(search): explain which address mode on verifies [docs-only] With OC_GRPC_CLIENT_TLS_MODE=on the certificate is checked against the dialed address, which is now SEARCH_GRPC_ADDR by default. A bind address such as 0.0.0.0:9220 then fails verification unless --endpoint names a host the certificate is valid for. --- services/search/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/search/README.md b/services/search/README.md index 96bdc00c21..9f7adb0bd5 100644 --- a/services/search/README.md +++ b/services/search/README.md @@ -134,6 +134,8 @@ Please note that a reindex only picks up new or changed files. Files that have a opencloud search index --all-spaces --force-rescan ``` +The command connects to the service's gRPC address (`SEARCH_GRPC_ADDR`) unless `--endpoint` is given, with the TLS mode set in `OC_GRPC_CLIENT_TLS_MODE`. With `on`, the server certificate is verified against that address, so if `SEARCH_GRPC_ADDR` is a bind address such as `0.0.0.0:9220`, pass `--endpoint` with a host name the certificate is valid for. + ## Metrics The search service exposes the following prometheus metrics at `/metrics` (as configured using the `SEARCH_DEBUG_ADDR` env var): From 5c39a40f6b7ede692655fe5cd111c36ee1c6ca86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 18:41:53 +0200 Subject: [PATCH 09/19] refactor(search): restore the endpointFlag name The Flag suffix is the convention for the command's flag variables, not only for booleans. --- services/search/pkg/command/index.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/search/pkg/command/index.go b/services/search/pkg/command/index.go index 0da05850ba..2363d2a73c 100644 --- a/services/search/pkg/command/index.go +++ b/services/search/pkg/command/index.go @@ -31,7 +31,7 @@ func Index(cfg *config.Config) *cobra.Command { allSpacesFlag, _ := cmd.Flags().GetBool("all-spaces") spaceFlag, _ := cmd.Flags().GetString("space") forceRescanFlag, _ := cmd.Flags().GetBool("force-rescan") - endpoint, _ := cmd.Flags().GetString("endpoint") + endpointFlag, _ := cmd.Flags().GetString("endpoint") insecureFlag, _ := cmd.Flags().GetBool("insecure") concurrencyFlag, _ := cmd.Flags().GetInt("concurrency") @@ -43,7 +43,7 @@ func Index(cfg *config.Config) *cobra.Command { } if !cmd.Flags().Changed("endpoint") { - endpoint = cfg.GRPC.Addr + endpointFlag = cfg.GRPC.Addr } tlsMode := pool.TLSOff @@ -55,12 +55,12 @@ func Index(cfg *config.Config) *cobra.Command { tlsMode = mode } - conn, err := pool.NewConn(endpoint, + conn, err := pool.NewConn(endpointFlag, pool.WithTLSMode(tlsMode), pool.WithTLSCACert(cfg.GRPCClientTLS.CACert), ) if err != nil { - return fmt.Errorf("failed to dial %s: %w", endpoint, err) + return fmt.Errorf("failed to dial %s: %w", endpointFlag, err) } defer conn.Close() From 283bbe4ee3a4a99a8d7da27213457a6bce39a544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Sat, 3 Oct 2026 18:41:53 +0200 Subject: [PATCH 10/19] docs(search): extend the --insecure note to 8.1.x [docs-only] 8.1.0 ships before this fix, so it still needs the flag too. --- services/search/MIGRATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/search/MIGRATION.md b/services/search/MIGRATION.md index 12ad80a673..9d9589be0f 100644 --- a/services/search/MIGRATION.md +++ b/services/search/MIGRATION.md @@ -8,7 +8,7 @@ until you remove it. ## v7.x.x to v8.x.x > [!IMPORTANT] -> On 8.0.0 and 8.0.1, `opencloud search index` needs `--insecure` in the +> On 8.0.x and 8.1.x, `opencloud search index` needs `--insecure` in the > default setup, where the search service runs gRPC without TLS: add it to the > commands below. Later releases don't need it. From abb00f01c9fcad9e41d104b055fa94a09401675a Mon Sep 17 00:00:00 2001 From: Ryo Kusnadi Date: Wed, 4 Nov 2026 05:18:59 +0700 Subject: [PATCH 11/19] fix(antivirus): treat a clamd ERROR reply as a failed scan Signed-off-by: Ryo Kusnadi --- services/antivirus/pkg/scanners/clamav.go | 6 ++++++ .../antivirus/pkg/scanners/clamav_test.go | 21 +++++++++++++++++++ services/antivirus/pkg/scanners/scanners.go | 2 ++ 3 files changed, 29 insertions(+) diff --git a/services/antivirus/pkg/scanners/clamav.go b/services/antivirus/pkg/scanners/clamav.go index 9af56cc4a9..f8db072878 100644 --- a/services/antivirus/pkg/scanners/clamav.go +++ b/services/antivirus/pkg/scanners/clamav.go @@ -42,6 +42,12 @@ func (s ClamAV) Scan(in Input) (Result, error) { abort <- true return Result{}, fmt.Errorf("%w: %s", ErrScanTimeout, in.Url) case s := <-ch: + // only a definite answer counts: anything but OK or FOUND (ERROR, + // PARSE ERROR, ...) means the scan did not finish, so it must not pass as clean. + if s.Status != clamd.RES_OK && s.Status != clamd.RES_FOUND { + return Result{}, fmt.Errorf("%w: %s: %s", ErrScanFailed, s.Status, s.Description) + } + return Result{ Infected: s.Status == clamd.RES_FOUND, Description: s.Description, diff --git a/services/antivirus/pkg/scanners/clamav_test.go b/services/antivirus/pkg/scanners/clamav_test.go index 9326ff72c9..fa74aa0cce 100644 --- a/services/antivirus/pkg/scanners/clamav_test.go +++ b/services/antivirus/pkg/scanners/clamav_test.go @@ -95,6 +95,27 @@ func TestNewClamAV_Scan(t *testing.T) { assert.True(t, <-done) }) + t.Run("returns an error if clamd answers with an error", func(t *testing.T) { + for name, reply := range map[string]string{ + "ERROR": "stream: Can't write to file ERROR\n", + "PARSE ERROR": "stream: Some parse problem PARSE ERROR\n", + } { + t.Run(name, func(t *testing.T) { + ul := newUnixListener(t, net.ListenConfig{}, "PONG\n", reply) + defer func() { + assert.NoError(t, ul.Close()) + }() + + scanner, err := scanners.NewClamAV(ul.Addr().String(), 10*time.Second) + require.NoError(t, err) + + result, err := scanner.Scan(scanners.Input{Body: strings.NewReader("DATA")}) + assert.ErrorIs(t, err, scanners.ErrScanFailed) + assert.False(t, result.Infected) + }) + } + }) + t.Run("aborts after a certain time", func(t *testing.T) { ul := newUnixListener(t, net.ListenConfig{}, "PONG\n", "stream: Win.Test.EICAR_HDB-1 FOUND\n") defer func() { diff --git a/services/antivirus/pkg/scanners/scanners.go b/services/antivirus/pkg/scanners/scanners.go index 223bd4fc1d..d3df797371 100644 --- a/services/antivirus/pkg/scanners/scanners.go +++ b/services/antivirus/pkg/scanners/scanners.go @@ -9,6 +9,8 @@ import ( var ( // ErrScanTimeout is returned when a scan times out ErrScanTimeout = errors.New("time out waiting for clamav to respond while scanning") + // ErrScanFailed is returned when the scanner answers with an error instead of a verdict + ErrScanFailed = errors.New("scanner failed to scan the file") // ErrScannerNotReachable is returned when the scanner is not reachable ErrScannerNotReachable = errors.New("failed to reach the scanner") ) From fabb775d17542d510307369884d26025ae784536 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Duffeck?= Date: Wed, 11 Nov 2026 10:12:08 +0100 Subject: [PATCH 12/19] Fix panic when clamd hangs up without a scan result --- services/antivirus/pkg/scanners/clamav.go | 7 ++++++- services/antivirus/pkg/scanners/clamav_test.go | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/services/antivirus/pkg/scanners/clamav.go b/services/antivirus/pkg/scanners/clamav.go index f8db072878..e9dc3a283e 100644 --- a/services/antivirus/pkg/scanners/clamav.go +++ b/services/antivirus/pkg/scanners/clamav.go @@ -41,7 +41,12 @@ func (s ClamAV) Scan(in Input) (Result, error) { case <-time.After(s.timeout): abort <- true return Result{}, fmt.Errorf("%w: %s", ErrScanTimeout, in.Url) - case s := <-ch: + case s, ok := <-ch: + // go-clamd closes the channel without a result when clamd hangs up without replying + if !ok || s == nil { + return Result{}, fmt.Errorf("%w: no reply from clamd", ErrScanFailed) + } + // only a definite answer counts: anything but OK or FOUND (ERROR, // PARSE ERROR, ...) means the scan did not finish, so it must not pass as clean. if s.Status != clamd.RES_OK && s.Status != clamd.RES_FOUND { diff --git a/services/antivirus/pkg/scanners/clamav_test.go b/services/antivirus/pkg/scanners/clamav_test.go index fa74aa0cce..e6d723c7bc 100644 --- a/services/antivirus/pkg/scanners/clamav_test.go +++ b/services/antivirus/pkg/scanners/clamav_test.go @@ -116,6 +116,19 @@ func TestNewClamAV_Scan(t *testing.T) { } }) + t.Run("returns an error if clamd closes the connection without replying", func(t *testing.T) { + ul := newUnixListener(t, net.ListenConfig{}, "PONG\n", "") + defer func() { + assert.NoError(t, ul.Close()) + }() + + scanner, err := scanners.NewClamAV(ul.Addr().String(), 10*time.Second) + require.NoError(t, err) + + _, err = scanner.Scan(scanners.Input{Body: strings.NewReader("DATA")}) + assert.ErrorIs(t, err, scanners.ErrScanFailed) + }) + t.Run("aborts after a certain time", func(t *testing.T) { ul := newUnixListener(t, net.ListenConfig{}, "PONG\n", "stream: Win.Test.EICAR_HDB-1 FOUND\n") defer func() { From 6ef16a956948069d5b7a6f62c0324704c06c55d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Duffeck?= Date: Wed, 11 Nov 2026 11:11:02 +0100 Subject: [PATCH 13/19] Document that the max scan size must not exceed clamd's StreamMaxLength --- services/antivirus/pkg/config/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/antivirus/pkg/config/config.go b/services/antivirus/pkg/config/config.go index 32f89eb0b5..87288eab21 100644 --- a/services/antivirus/pkg/config/config.go +++ b/services/antivirus/pkg/config/config.go @@ -41,7 +41,7 @@ type Config struct { Workers int `yaml:"workers" env:"ANTIVIRUS_WORKERS" desc:"The number of concurrent go routines that fetch events from the event queue." introductionVersion:"1.0.0"` Scanner Scanner - MaxScanSize string `yaml:"max-scan-size" env:"ANTIVIRUS_MAX_SCAN_SIZE" desc:"The maximum scan size the virus scanner can handle.0 means unlimited. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB, TB, TiB, PB, PiB, EB, EiB], example: 2GB." introductionVersion:"1.0.0"` + MaxScanSize string `yaml:"max-scan-size" env:"ANTIVIRUS_MAX_SCAN_SIZE" desc:"The maximum scan size the virus scanner can handle. 0 means unlimited. When using ClamAV, keep it at or below clamd's StreamMaxLength, otherwise clamd refuses bigger files and their uploads fail after the postprocessing retries. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB, TB, TiB, PB, PiB, EB, EiB], example: 2GB." introductionVersion:"1.0.0"` MaxScanSizeMode MaxScanSizeMode `yaml:"max-scan-size-mode" env:"ANTIVIRUS_MAX_SCAN_SIZE_MODE" desc:"Defines the mode of handling files that exceed the maximum scan size. Supported options are: 'skip', which skips files that are bigger than the max scan size, and 'truncate' (default), which only uses the file up to the max size." introductionVersion:"2.1.0"` Context context.Context `json:"-" yaml:"-"` From 4d9cf370e7cf0c5fe33ad7bd67cac34da22f9cb3 Mon Sep 17 00:00:00 2001 From: Viktor Scharf Date: Wed, 11 Nov 2026 14:07:59 +0100 Subject: [PATCH 14/19] chore: bump web to v8.2.2 (#3962) --- .woodpecker.env | 2 +- services/web/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.woodpecker.env b/.woodpecker.env index a25eb8e5d7..e044d2f8b9 100644 --- a/.woodpecker.env +++ b/.woodpecker.env @@ -1,3 +1,3 @@ # The test runner source for UI tests -WEB_COMMITID=dd976185323c9f1e1528b77179f18141aeeec2c4 +WEB_COMMITID=ee3d8b09efe1ce5578d4f0651a76e42cab5020fe WEB_BRANCH=main diff --git a/services/web/Makefile b/services/web/Makefile index 087d50ad50..688d1f4172 100644 --- a/services/web/Makefile +++ b/services/web/Makefile @@ -1,6 +1,6 @@ SHELL := bash NAME := web -WEB_ASSETS_VERSION = v8.2.2-beta.1 +WEB_ASSETS_VERSION = v8.2.2 WEB_ASSETS_BRANCH = main ifneq (, $(shell command -v go 2> /dev/null)) # suppress `command not found warnings` for non go targets in CI From 2435420f69caae7b63f4c6307f73fec221e3d0f1 Mon Sep 17 00:00:00 2001 From: Viktor Scharf Date: Wed, 11 Nov 2026 14:14:34 +0100 Subject: [PATCH 15/19] [full-ci] chore: bump reva to 2.52.2 (#3955) * chore: bump reva to 2.52.2 * Merge pull request #42 from opencloud-eu/fix-web-theme-merge fix(web): merge copies of the theme sources so themeDefaults is never mutated * Merge pull request #43 from opencloud-eu/fix-search-trailing-not fix(search): handle missing operands in the bleve compiler * Merge pull request #44 from opencloud-eu/fix-search-highlight-escaping fix(search): escape file content in OpenSearch highlights --------- Co-authored-by: Ralf Haferkamp Co-authored-by: Florian Schade --- go.mod | 12 +- go.sum | 28 +- pkg/version/version.go | 2 +- services/collaboration/pkg/config/http.go | 4 +- services/proxy/pkg/config/config.go | 4 +- services/search/pkg/content/content.go | 2 +- services/search/pkg/content/content_test.go | 8 + services/search/pkg/opensearch/backend.go | 1 + services/search/pkg/parity/README.md | 4 + .../search/pkg/parity/response_entity_test.go | 12 +- services/search/pkg/query/bleve/compiler.go | 5 + .../search/pkg/query/bleve/compiler_test.go | 22 +- services/search/pkg/search/service.go | 31 +- services/search/pkg/search/service_test.go | 39 +- services/userlog/pkg/config/config.go | 4 +- services/web/pkg/theme/kv.go | 8 +- services/web/pkg/theme/kv_test.go | 91 + services/web/pkg/theme/service_test.go | 68 + vendor/github.com/go-chi/chi/v5/README.md | 86 +- vendor/github.com/go-chi/chi/v5/chi.go | 16 +- vendor/github.com/go-chi/chi/v5/context.go | 38 +- .../go-chi/chi/v5/middleware/client_ip.go | 133 +- .../go-chi/chi/v5/middleware/compress.go | 18 +- .../chi/v5/middleware/content_charset.go | 6 + .../go-chi/chi/v5/middleware/logger.go | 10 +- .../go-chi/chi/v5/middleware/recoverer.go | 6 +- .../go-chi/chi/v5/middleware/terminal.go | 2 +- .../go-chi/chi/v5/middleware/value.go | 2 +- .../go-chi/chi/v5/middleware/wrap_writer.go | 24 +- vendor/github.com/go-chi/chi/v5/mux.go | 10 +- vendor/github.com/go-chi/chi/v5/tree.go | 4 +- .../github.com/go-jose/go-jose/v4/crypter.go | 15 + vendor/github.com/go-jose/go-jose/v4/jwe.go | 18 +- vendor/github.com/go-jose/go-jose/v4/jwk.go | 51 +- vendor/github.com/go-jose/go-jose/v4/jws.go | 31 +- .../github.com/go-jose/go-jose/v4/shared.go | 31 +- .../go-jose/go-jose/v4/tests.Containerfile | 13 + .../go-jose/go-jose/v4/threat_model.md | 25 + .../go-playground/locales/README.md | 12 +- .../github.com/go-playground/locales/en/en.go | 28 +- .../github.com/go-playground/locales/rules.go | 23 +- .../go-playground/validator/v10/.gitignore | 2 + .../validator/v10/.golangci.yaml | 1 + .../go-playground/validator/v10/Makefile | 2 +- .../go-playground/validator/v10/README.md | 3 +- .../go-playground/validator/v10/baked_in.go | 37 +- .../go-playground/validator/v10/doc.go | 20 +- .../validator/v10/translations/en/en.go | 62 +- vendor/github.com/leodido/go-urn/machine.go | 6 +- .../github.com/leodido/go-urn/machine.go.rl | 8 +- vendor/github.com/leodido/go-urn/urn.go | 8 +- .../eventsmiddleware/conversion.go | 2 +- .../auth/credential/strategy/basic/basic.go | 2 +- .../auth/credential/strategy/bearer/bearer.go | 2 +- .../http/services/owncloud/ocdav/dav.go | 4 +- .../owncloud/ocdav/propfind/propfind.go | 2 + .../http/services/sciencemesh/wayf.go | 88 +- .../reva/v2/pkg/auth/challenge.go | 14 + .../reva/v2/pkg/conversions/main.go | 3 + .../opencloud-eu/reva/v2/pkg/mime/mime.go | 19 +- .../v2/pkg/rhttp/datatx/metrics/metrics.go | 22 +- .../jsoncs3/providercache/providercache.go | 2 +- .../receivedsharecache/receivedsharecache.go | 2 +- .../manager/jsoncs3/sharecache/sharecache.go | 2 +- .../reva/v2/pkg/storage/fs/loader/loader.go | 2 - .../storage/fs/ocis/blobstore/blobstore.go | 199 --- .../reva/v2/pkg/storage/fs/ocis/ocis.go | 51 - .../pkg/storage/fs/posix/trashbin/trashbin.go | 4 + .../storage/fs/s3ng/blobstore/blobstore.go | 179 -- .../reva/v2/pkg/storage/fs/s3ng/option.go | 93 - .../reva/v2/pkg/storage/fs/s3ng/s3ng.go | 63 - .../storage/pkg/decomposedfs/decomposedfs.go | 4 +- .../decomposedfs/metadata/hybrid_backend.go | 24 +- .../storage/pkg/decomposedfs/metadata/lock.go | 46 + .../metadata/messagepack_backend.go | 12 +- .../pkg/decomposedfs/metadata/metrics.go | 92 + .../decomposedfs/metadata/xattrs_backend.go | 22 +- .../pkg/storage/pkg/decomposedfs/node/node.go | 27 +- .../pkg/decomposedfs/options/options.go | 4 +- .../pkg/storage/pkg/decomposedfs/recycle.go | 3 + .../v2/pkg/storage/pkg/decomposedfs/spaces.go | 84 +- .../pkg/decomposedfs/tree/propagator/async.go | 5 + .../decomposedfs/tree/propagator/metrics.go | 40 + .../pkg/decomposedfs/tree/propagator/sync.go | 5 + .../utils/decomposedfs/aspects/aspects.go | 38 - .../utils/decomposedfs/decomposedfs.go | 1359 -------------- .../pkg/storage/utils/decomposedfs/grants.go | 361 ---- .../utils/decomposedfs/lookup/lookup.go | 412 ----- .../storage/utils/decomposedfs/metadata.go | 224 --- .../utils/decomposedfs/metadata/errors.go | 99 -- .../utils/decomposedfs/metadata/list.go | 55 - .../metadata/messagepack_backend.go | 330 ---- .../utils/decomposedfs/metadata/metadata.go | 129 -- .../metadata/prefixes/ocis_prefix.go | 29 - .../metadata/prefixes/ocis_prefix_freebsd.go | 28 - .../metadata/prefixes/prefixes.go | 102 -- .../decomposedfs/metadata/xattrs_backend.go | 302 ---- .../0001_create_spaces_directory_structure.go | 138 -- .../0002_move_spacetypes_to_indexes.go | 150 -- .../0003_switch_to_messagepack_metadata.go | 120 -- .../0004_switch_to_messagepack_space_index.go | 203 --- ...0005_fix_messagepack_space_index_format.go | 114 -- .../utils/decomposedfs/migrator/migrator.go | 217 --- .../decomposedfs/mtimesyncedcache/map.go | 45 - .../mtimesyncedcache/mtimesyncedcache.go | 59 - .../storage/utils/decomposedfs/node/locks.go | 360 ---- .../storage/utils/decomposedfs/node/node.go | 1561 ----------------- .../utils/decomposedfs/node/node_unix.go | 38 - .../utils/decomposedfs/node/node_windows.go | 38 - .../utils/decomposedfs/node/permissions.go | 232 --- .../storage/utils/decomposedfs/node/xattrs.go | 222 --- .../utils/decomposedfs/options/options.go | 176 -- .../permissions/spacepermissions.go | 169 -- .../pkg/storage/utils/decomposedfs/recycle.go | 460 ----- .../storage/utils/decomposedfs/revisions.go | 413 ----- .../decomposedfs/spaceidindex/spaceidindex.go | 159 -- .../pkg/storage/utils/decomposedfs/spaces.go | 1141 ------------ .../decomposedfs/timemanager/timemanager.go | 127 -- .../utils/decomposedfs/trashbin/trashbin.go | 35 - .../decomposedfs/tree/propagator/async.go | 439 ----- .../tree/propagator/propagator.go | 101 -- .../decomposedfs/tree/propagator/sync.go | 209 --- .../storage/utils/decomposedfs/tree/tree.go | 982 ----------- .../pkg/storage/utils/decomposedfs/upload.go | 522 ------ .../utils/decomposedfs/upload/session.go | 358 ---- .../utils/decomposedfs/upload/store.go | 423 ----- .../utils/decomposedfs/upload/upload.go | 427 ----- .../decomposedfs/usermapper/usermapper.go | 56 - .../usermapper/usermapper_linux.go | 131 -- .../storage/utils/middleware/middleware.go | 7 +- .../opencloud-eu/reva/v2/pkg/tags/tags.go | 1 + vendor/modules.txt | 39 +- 132 files changed, 1272 insertions(+), 14287 deletions(-) create mode 100644 vendor/github.com/go-jose/go-jose/v4/tests.Containerfile create mode 100644 vendor/github.com/go-jose/go-jose/v4/threat_model.md create mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/auth/challenge.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore/blobstore.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/ocis.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore/blobstore.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/option.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/s3ng.go create mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/lock.go create mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/metrics.go create mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/metrics.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects/aspects.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/decomposedfs.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/grants.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup/lookup.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/errors.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/list.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/messagepack_backend.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/metadata.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix_freebsd.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/prefixes.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/xattrs_backend.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0001_create_spaces_directory_structure.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0002_move_spacetypes_to_indexes.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0003_switch_to_messagepack_metadata.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0004_switch_to_messagepack_space_index.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0005_fix_messagepack_space_index_format.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/migrator.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/map.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/mtimesyncedcache.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/locks.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_unix.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_windows.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/permissions.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/xattrs.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options/options.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions/spacepermissions.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/recycle.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/revisions.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex/spaceidindex.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaces.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager/timemanager.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin/trashbin.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/async.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/propagator.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/sync.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/tree.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/session.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/store.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/upload.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper.go delete mode 100644 vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper_linux.go diff --git a/go.mod b/go.mod index 90d16363fb..eca557de2d 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e github.com/gabriel-vasile/mimetype v1.4.15 github.com/ggwhite/go-masker v1.1.0 - github.com/go-chi/chi/v5 v5.3.2 + github.com/go-chi/chi/v5 v5.4.0 github.com/go-chi/render v1.0.3 github.com/go-ldap/ldap/v3 v3.4.15 github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3 @@ -33,7 +33,7 @@ require ( github.com/go-micro/plugins/v4/store/nats-js-kv v0.0.0-20240726082623-6831adfdcdc4 github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0 github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0 - github.com/go-playground/validator/v10 v10.30.3 + github.com/go-playground/validator/v10 v10.30.5 github.com/go-resty/resty/v2 v2.17.2 github.com/go-viper/mapstructure/v2 v2.5.0 github.com/gofrs/flock v0.13.1 @@ -68,7 +68,7 @@ require ( github.com/open-policy-agent/opa v1.21.1 github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 - github.com/opencloud-eu/reva/v2 v2.52.1 + github.com/opencloud-eu/reva/v2 v2.52.2 github.com/opensearch-project/opensearch-go/v4 v4.7.3 github.com/orcaman/concurrent-map v1.0.0 github.com/pkg/errors v0.9.1 @@ -209,7 +209,7 @@ require ( github.com/go-git/go-billy/v5 v5.9.1 // indirect github.com/go-git/go-git/v5 v5.19.2 // indirect github.com/go-jose/go-jose/v3 v3.0.5 // indirect - github.com/go-jose/go-jose/v4 v4.1.5 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-logr/logr v1.4.4 // indirect @@ -218,7 +218,7 @@ require ( github.com/go-micro/plugins/v4/store/nats-js v1.2.1 // indirect github.com/go-micro/plugins/v4/store/redis v1.2.1 // indirect github.com/go-ole/go-ole v1.3.0 // indirect - github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/locales v0.14.2 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect github.com/go-redis/redis/v8 v8.11.5 // indirect github.com/go-sql-driver/mysql v1.10.1 // indirect @@ -259,7 +259,7 @@ require ( github.com/klauspost/crc32 v1.3.0 // indirect github.com/kovidgoyal/go-parallel v1.1.1 // indirect github.com/kovidgoyal/go-shm v1.0.0 // indirect - github.com/leodido/go-urn v1.4.0 // indirect + github.com/leodido/go-urn v1.5.0 // indirect github.com/lestrrat-go/blackmagic v1.0.4 // indirect github.com/lestrrat-go/dsig v1.4.0 // indirect github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect diff --git a/go.sum b/go.sum index c66e3cb7fe..335ac484cb 100644 --- a/go.sum +++ b/go.sum @@ -305,8 +305,8 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ= github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= -github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= -github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/go-chi/chi/v5 v5.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE= +github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4= github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= @@ -323,8 +323,8 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2 github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ= github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA= -github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= +github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= @@ -373,12 +373,12 @@ github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= +github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8= -github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc= +github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= +github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk= @@ -610,8 +610,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/leonelquinteros/gotext v1.7.3-0.20260422134830-b012b4ccae69 h1:ZLo0bXX17iUZpb/Sp7N+1uK4Jb7dl0fm5x5ETfzYSvY= github.com/leonelquinteros/gotext v1.7.3-0.20260422134830-b012b4ccae69/go.mod h1:ksG5iXViKefoupjy+0qQjAVoaDnylnQ1ejWl9g14wh8= github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA= @@ -761,8 +761,8 @@ github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89 h1:W1ms+l github.com/opencloud-eu/icap-client v0.0.0-20250930132611-28a2afe62d89/go.mod h1:vigJkNss1N2QEceCuNw/ullDehncuJNFB6mEnzfq9UI= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 h1:3ptbiFhSK4fzY/rC3idcYUveiwepMoOov1sBpc7Rg3k= github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346/go.mod h1:lTM8JeGblNpoMySTW7Lui2+c5TTLI95mwxtdUIHHrhU= -github.com/opencloud-eu/reva/v2 v2.52.1 h1:c4tjmqtbJeqDjztTNq4Jvl3dWWSMHhXqV1JixKLKbT4= -github.com/opencloud-eu/reva/v2 v2.52.1/go.mod h1:rAwuI3PX8n3RxBXHfpMtAKqfwxTIKhZol1Bi3Qj39p8= +github.com/opencloud-eu/reva/v2 v2.52.2 h1:uSYHhzX9hv911ciAyCVShg99cUoudkmFu+WVK2G85eI= +github.com/opencloud-eu/reva/v2 v2.52.2/go.mod h1:jqg3kpCQTwagdcnu/D+resnrnNzSg6cjAQ/Wv4fmvBI= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4 h1:l2oB/RctH+t8r7QBj5p8thfEHCM/jF35aAY3WQ3hADI= github.com/opencloud-eu/secure v0.0.0-20260312082735-b6f5cb2244e4/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= @@ -951,8 +951,8 @@ github.com/testcontainers/testcontainers-go/modules/opensearch v0.44.0 h1:iuBDo8 github.com/testcontainers/testcontainers-go/modules/opensearch v0.44.0/go.mod h1:8Qw29ffsCPzhomxqoeGhpj3J3Lbsrv0FsOUWeOjTl+I= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= -github.com/thanhpk/randstr v1.0.6 h1:psAOktJFD4vV9NEVb3qkhRSMvYh4ORRaj1+w/hn4B+o= -github.com/thanhpk/randstr v1.0.6/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U= +github.com/thanhpk/randstr v1.0.7 h1:tfsKHOb2hkJVJoguakWQ0IYDGM9BsBcFIpJdmIoQp9M= +github.com/thanhpk/randstr v1.0.7/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U= github.com/thejerf/suture/v4 v4.0.6 h1:QsuCEsCqb03xF9tPAsWAj8QOAJBgQI1c0VqJNaingg8= github.com/thejerf/suture/v4 v4.0.6/go.mod h1:gu9Y4dXNUWFrByqRt30Rm9/UZ0wzRSt9AJS6xu/ZGxU= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= diff --git a/pkg/version/version.go b/pkg/version/version.go index 5ebb057088..1fdd6e3f93 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -34,7 +34,7 @@ var ( // LatestTag is the latest released version plus the dev meta version. // Will be overwritten by the release pipeline // Needs a manual change for every tagged release - LatestTag = "9.0.0+dev" + LatestTag = "9.1.0+dev" // Date indicates the build date. // This has been removed, it looks like you can only replace static strings with recent go versions diff --git a/services/collaboration/pkg/config/http.go b/services/collaboration/pkg/config/http.go index 6a9c6c762e..da5847691f 100644 --- a/services/collaboration/pkg/config/http.go +++ b/services/collaboration/pkg/config/http.go @@ -9,6 +9,6 @@ type HTTP struct { Addr string `yaml:"addr" env:"COLLABORATION_HTTP_ADDR" desc:"The bind address of the HTTP service." introductionVersion:"1.0.0"` Namespace string `yaml:"-"` TLS shared.HTTPServiceTLS `yaml:"tls"` - TrustedProxies []string `yaml:"trusted_proxies" env:"OC_TRUSTED_PROXIES;COLLABORATION_HTTP_TRUSTED_PROXIES" desc:"IP addresses and CIDR ranges of the reverse proxies in front of the collaboration service. The client address in the access log is only taken from the header set in COLLABORATION_HTTP_CLIENT_IP_HEADER if the request comes from one of these. Defaults to the loopback and private network ranges. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"` - ClientIPHeader string `yaml:"client_ip_header" env:"OC_CLIENT_IP_HEADER;COLLABORATION_HTTP_CLIENT_IP_HEADER" desc:"The header a trusted reverse proxy sends the client address in, e.g. X-Real-IP or CF-Connecting-IP. X-Forwarded-For is read from the right, the first address that is not a trusted proxy is the client." introductionVersion:"%%NEXT%%"` + TrustedProxies []string `yaml:"trusted_proxies" env:"OC_TRUSTED_PROXIES;COLLABORATION_HTTP_TRUSTED_PROXIES" desc:"IP addresses and CIDR ranges of the reverse proxies in front of the collaboration service. The client address in the access log is only taken from the header set in COLLABORATION_HTTP_CLIENT_IP_HEADER if the request comes from one of these. Defaults to the loopback and private network ranges. See the Environment Variable Types description for more details." introductionVersion:"9.1.0"` + ClientIPHeader string `yaml:"client_ip_header" env:"OC_CLIENT_IP_HEADER;COLLABORATION_HTTP_CLIENT_IP_HEADER" desc:"The header a trusted reverse proxy sends the client address in, e.g. X-Real-IP or CF-Connecting-IP. X-Forwarded-For is read from the right, the first address that is not a trusted proxy is the client." introductionVersion:"9.1.0"` } diff --git a/services/proxy/pkg/config/config.go b/services/proxy/pkg/config/config.go index a5a6522220..83293cbac7 100644 --- a/services/proxy/pkg/config/config.go +++ b/services/proxy/pkg/config/config.go @@ -100,8 +100,8 @@ var ( // ClientIP configures how the proxy determines the address of the client. type ClientIP struct { - TrustedProxies []string `yaml:"trusted_proxies" env:"OC_TRUSTED_PROXIES;PROXY_TRUSTED_PROXIES" desc:"IP addresses and CIDR ranges of the reverse proxies in front of OpenCloud. The client address is only taken from the header set in PROXY_CLIENT_IP_HEADER if the request comes from one of these. Defaults to the loopback and private network ranges. Set it to the addresses of your reverse proxies if clients can reach OpenCloud from a private network. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"` - Header string `yaml:"header" env:"OC_CLIENT_IP_HEADER;PROXY_CLIENT_IP_HEADER" desc:"The header a trusted reverse proxy sends the client address in, e.g. X-Real-IP or CF-Connecting-IP. X-Forwarded-For is read from the right, the first address that is not a trusted proxy is the client." introductionVersion:"%%NEXT%%"` + TrustedProxies []string `yaml:"trusted_proxies" env:"OC_TRUSTED_PROXIES;PROXY_TRUSTED_PROXIES" desc:"IP addresses and CIDR ranges of the reverse proxies in front of OpenCloud. The client address is only taken from the header set in PROXY_CLIENT_IP_HEADER if the request comes from one of these. Defaults to the loopback and private network ranges. Set it to the addresses of your reverse proxies if clients can reach OpenCloud from a private network. See the Environment Variable Types description for more details." introductionVersion:"9.1.0"` + Header string `yaml:"header" env:"OC_CLIENT_IP_HEADER;PROXY_CLIENT_IP_HEADER" desc:"The header a trusted reverse proxy sends the client address in, e.g. X-Real-IP or CF-Connecting-IP. X-Forwarded-For is read from the right, the first address that is not a trusted proxy is the client." introductionVersion:"9.1.0"` } // AuthMiddleware configures the proxy http auth middleware. diff --git a/services/search/pkg/content/content.go b/services/search/pkg/content/content.go index 6a945b0fd3..2ba6a871cb 100644 --- a/services/search/pkg/content/content.go +++ b/services/search/pkg/content/content.go @@ -33,5 +33,5 @@ type Document struct { } func CleanString(content, langCode string) string { - return strings.TrimSpace(stopwords.CleanString(content, langCode, true)) + return strings.TrimSpace(stopwords.CleanString(content, langCode, false)) } diff --git a/services/search/pkg/content/content_test.go b/services/search/pkg/content/content_test.go index 389dcd001c..6e12592529 100644 --- a/services/search/pkg/content/content_test.go +++ b/services/search/pkg/content/content_test.go @@ -25,6 +25,14 @@ func TestCleanContent(t *testing.T) { given: "content contains https://localhost/remote.php/dav/files/admin/Photos/San%20Francisco.jpg and stop word", expect: "content contains https://localhost/remote.php/dav/files/admin/photos/san%20francisco.jpg stop word", }, + { + given: "needle <img src=x> needle", + expect: "needle <img src=x> needle", + }, + { + given: "List names from Alice ", + expect: "list names alice ", + }, } for _, tc := range tests { diff --git a/services/search/pkg/opensearch/backend.go b/services/search/pkg/opensearch/backend.go index 330dcd577d..2e6e0eccb9 100644 --- a/services/search/pkg/opensearch/backend.go +++ b/services/search/pkg/opensearch/backend.go @@ -130,6 +130,7 @@ func (b *Backend) Search(ctx context.Context, sir *searchService.SearchIndexRequ osu.SearchBodyParams{ Highlight: &osu.BodyParamHighlight{ HighlightOptions: osu.HighlightOptions{ + Encoder: "html", NumberOfFragments: 2, PreTags: []string{""}, PostTags: []string{""}, diff --git a/services/search/pkg/parity/README.md b/services/search/pkg/parity/README.md index db58fa0d11..8980d7c439 100644 --- a/services/search/pkg/parity/README.md +++ b/services/search/pkg/parity/README.md @@ -748,6 +748,8 @@ Fixtures: - `parent`, ID = 1$1!2, folder - `bar.pdf`, ID = 1$1!3, MimeType = application/pdf, Path = ./parent/bar.pdf, Size = 1234 - `notes.txt`, ID = 1$1!4, Content = "foo bar baz" +- `markup.txt`, ID = 1$1!5, Content = "foo qux" +- `escaped.txt`, ID = 1$1!6, Content = "foo <img src=x> zap" | Case | Query | expected | bleve | OpenSearch | same? | |---|---|---|---|---|---| @@ -764,6 +766,8 @@ Fixtures: | ENTITY-11 | `path:"./parent"` reads `TotalMatches` | 2 | 2 | 2 | ✅ | | ENTITY-12 | `name:"*notes*"` reads `Highlights` | "" | "" | "" | ✅ | | ENTITY-13 | `content:bar` reads `Highlights` | foo bar baz | foo bar baz | foo bar baz | ✅ | +| ENTITY-17 | `content:qux` reads `Highlights` | foo <im...x | foo <im...x | foo <im...x | ✅ | +| ENTITY-18 | `content:zap` reads `Highlights` | foo &l...p | foo &l...p | foo &l...p | ✅ | | ENTITY-14 | moved to another parent, then `name:"newname"` reads `ParentId` | 1$1!9 | 1$1!9 | 1$1!9 | ✅ | | ENTITY-15 | moved to another parent, then `name:"bar.pdf"` reads `ParentId` | 1$1!2 | 1$1!2 | 1$1!2 | ✅ | | ENTITY-16 | moved to another parent, then `name:"bar.pdf"` reads `Ref.Path` | ./somewher.../bar.pdf | ./somewher.../bar.pdf | ./somewher.../bar.pdf | ✅ | diff --git a/services/search/pkg/parity/response_entity_test.go b/services/search/pkg/parity/response_entity_test.go index c32ecbf5df..ad761de7ec 100644 --- a/services/search/pkg/parity/response_entity_test.go +++ b/services/search/pkg/parity/response_entity_test.go @@ -18,12 +18,14 @@ func entityGroup() responseGroup { withSize(1234), ) notes := fixtureDoc("notes.txt", withID("1$1!4"), withContent("foo bar baz")) + markup := fixtureDoc("markup.txt", withID("1$1!5"), withContent("foo qux")) + escaped := fixtureDoc("escaped.txt", withID("1$1!6"), withContent("foo <img src=x> zap")) moved := func(e search.Engine) error { return e.Move(parent.ID, "1$1!9", "./somewhere/newname") } return responseGroup{ name: "entity", - fixtures: []search.Resource{parent, doc, notes}, + fixtures: []search.Resource{parent, doc, notes, markup, escaped}, cases: []responseCase{ { id: 1, query: `name:"bar.pdf"`, reads: "Ref.Path", want: []string{"./parent/bar.pdf"}, @@ -85,6 +87,14 @@ func entityGroup() responseGroup { id: 13, query: `content:bar`, reads: "Highlights", want: []string{"foo bar baz"}, read: reads(func(m *searchMessage.Match) string { return m.GetEntity().GetHighlights() }), }, + { + id: 17, query: `content:qux`, reads: "Highlights", want: []string{"foo <img src=x> qux"}, + read: reads(func(m *searchMessage.Match) string { return m.GetEntity().GetHighlights() }), + }, + { + id: 18, query: `content:zap`, reads: "Highlights", want: []string{"foo &lt;img src=x&gt; zap"}, + read: reads(func(m *searchMessage.Match) string { return m.GetEntity().GetHighlights() }), + }, { id: 14, do: moved, after: "moved to another parent", query: `name:"newname"`, reads: "ParentId", want: []string{"1$1!9"}, read: reads(func(m *searchMessage.Match) string { return resourceID(m.GetEntity().GetParentId()) }), diff --git a/services/search/pkg/query/bleve/compiler.go b/services/search/pkg/query/bleve/compiler.go index 07117416f2..6a4229bc9b 100644 --- a/services/search/pkg/query/bleve/compiler.go +++ b/services/search/pkg/query/bleve/compiler.go @@ -8,6 +8,7 @@ import ( "github.com/blevesearch/bleve/v2" bleveQuery "github.com/blevesearch/bleve/v2/search/query" + "github.com/opencloud-eu/opencloud/pkg/ast" "github.com/opencloud-eu/opencloud/pkg/kql" "github.com/opencloud-eu/opencloud/services/search/pkg/mapping" @@ -276,6 +277,10 @@ func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) { } func nextNode(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) { + if offset >= len(nodes) { + return nil, 0, fmt.Errorf("operator without an operand") + } + if n, ok := nodes[offset].(*ast.GroupNode); ok { // keys are resolved and group keys propagated by normalize gq, _, err := walk(0, n.Nodes) diff --git a/services/search/pkg/query/bleve/compiler_test.go b/services/search/pkg/query/bleve/compiler_test.go index 095cb153ca..ec63d1e08d 100644 --- a/services/search/pkg/query/bleve/compiler_test.go +++ b/services/search/pkg/query/bleve/compiler_test.go @@ -6,9 +6,10 @@ import ( "time" "github.com/blevesearch/bleve/v2/search/query" + tAssert "github.com/stretchr/testify/assert" + "github.com/opencloud-eu/opencloud/pkg/ast" searchquery "github.com/opencloud-eu/opencloud/services/search/pkg/query" - tAssert "github.com/stretchr/testify/assert" ) var timeMustParse = func(t *testing.T, ts string) time.Time { @@ -623,6 +624,25 @@ func Test_compile(t *testing.T) { }), wantErr: false, }, + { + name: `missing right operand`, + args: &ast.Ast{ + Nodes: []ast.Node{ + &ast.StringNode{Value: "foo"}, + &ast.OperatorNode{Value: "NOT"}, + }, + }, + wantErr: true, + }, + { + name: `no operands`, + args: &ast.Ast{ + Nodes: []ast.Node{ + &ast.OperatorNode{Value: "NOT"}, + }, + }, + wantErr: true, + }, } assert := tAssert.New(t) diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 75741bf52d..49b2b4e5a9 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "html" "path/filepath" "reflect" "sort" @@ -346,7 +347,15 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se }, nil } -func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, space *provider.StorageSpace, mountpointID string) (*searchsvc.SearchIndexResponse, error) { +func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, space *provider.StorageSpace, mountpointID string) (res *searchsvc.SearchIndexResponse, err error) { + // the workers run in an errgroup, which does not recover, one failing space must not affect the others + defer func() { + if r := recover(); r != nil { + s.logger.Error().Interface("recover", r).Str("space", space.GetId().GetOpaqueId()).Str("query", req.GetQuery()).Msg("failed to search a space") + res, err = nil, errSkipSpace + } + }() + if req.Ref != nil && (req.Ref.ResourceId.StorageId != space.Root.StorageId || req.Ref.ResourceId.SpaceId != space.Root.SpaceId) { @@ -451,7 +460,7 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, PageSize: req.PageSize, } start := time.Now() - res, err := s.engine.Search(ctx, searchRequest) + res, err = s.engine.Search(ctx, searchRequest) duration := time.Since(start) if err != nil { s.logger.Error().Err(err).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Msg("failed to search the index") @@ -474,6 +483,7 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, } match.Entity.ShareRootName = rootName match.Entity.RemoteItemId = remoteItemId + match.Entity.Highlights = SanitizeHighlights(match.Entity.GetHighlights()) isShared := match.GetEntity().GetRef().GetResourceId().GetSpaceId() == utils.ShareStorageSpaceID isMountpoint := isShared && match.GetEntity().GetRef().GetPath() == "." @@ -782,6 +792,23 @@ func (s *Service) doUpsertItem(ctx context.Context, ref *provider.Reference, bat } } +// SanitizeHighlights keeps the tags and escapes everything else. +func SanitizeHighlights(highlights string) string { + var b strings.Builder + for i, open := range strings.Split(highlights, "") { + if i > 0 { + b.WriteString("") + } + for j, closed := range strings.Split(open, "") { + if j > 0 { + b.WriteString("") + } + b.WriteString(html.EscapeString(html.UnescapeString(closed))) + } + } + return b.String() +} + // IsHidden identifies if a node is hidden or not based on its name & path. func IsHidden(path string) bool { for name := range strings.SplitSeq(filepath.Clean(path), string(filepath.Separator)) { diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index ffccf65d04..03a03d38d3 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -291,6 +291,20 @@ var _ = Describe("Searchprovider", func() { Entry("a share fills neither", "grant", `(foo) AND NOT id:"none$none!none" AND NOT id:"none$none!none"`), ) + DescribeTable("SanitizeHighlights", + func(highlights, expected string) { + Expect(search.SanitizeHighlights(highlights)).To(Equal(expected)) + }, + Entry("plain text", "foo bar baz", "foo bar baz"), + Entry("raw markup", " bar", "<img src=x> bar"), + Entry("already escaped", "<img src=x> bar", "<img src=x> bar"), + Entry("escaped text from the file stays as typed", "&lt;img src=x&gt; bar", "&lt;img src=x&gt; bar"), + Entry("markup inside a mark", "bar", "<b>bar</b>"), + Entry("a mark with attributes", `bar`, "<mark class="x">bar"), + Entry("an escaped ampersand stays single", "Tom & Jerry", "Tom & Jerry"), + Entry("empty", "", ""), + ) + DescribeTable("IsHidden", func(path string, hidden bool) { Expect(search.IsHidden(path)).To(Equal(hidden)) @@ -337,7 +351,8 @@ var _ = Describe("Searchprovider", func() { StorageId: personalSpace.Root.StorageId, OpaqueId: "foo-id", }, - Name: "Foo.pdf", + Name: "Foo.pdf", + Highlights: `foo bar`, }, }, }, @@ -348,6 +363,15 @@ var _ = Describe("Searchprovider", func() { }, nil) }) + It("escapes the highlights whatever the engine returned", func() { + res, err := s.Search(ctx, &searchsvc.SearchRequest{ + Query: "bar", + }) + Expect(err).ToNot(HaveOccurred()) + Expect(res.Matches).To(HaveLen(1)) + Expect(res.Matches[0].Entity.Highlights).To(Equal(`foo <img src=x> bar`)) + }) + It("does not mess with field-based searches", func() { _, err := s.Search(ctx, &searchsvc.SearchRequest{ Query: "Size:<10", @@ -369,6 +393,19 @@ var _ = Describe("Searchprovider", func() { })) }) + It("continues with the remaining spaces when one fails", func() { + failingClient := &engineMocks.Engine{} + failingClient.On("Search", mock.Anything, mock.Anything).Run(func(mock.Arguments) { + panic("unexpected") + }).Return(nil, nil) + s := search.NewService(gatewaySelector, failingClient, extractor, nil, logger, &config.Config{}) + + res, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "foo"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res.TotalMatches).To(Equal(int32(0))) + Expect(res.Matches).To(BeEmpty()) + }) + It("searches the personal user space", func() { res, err := s.Search(ctx, &searchsvc.SearchRequest{ Query: "foo", diff --git a/services/userlog/pkg/config/config.go b/services/userlog/pkg/config/config.go index 1343547b28..147c65c375 100644 --- a/services/userlog/pkg/config/config.go +++ b/services/userlog/pkg/config/config.go @@ -53,7 +53,7 @@ type Persistence struct { // Events combines the configuration options for the event bus. type Events struct { - Disabled bool `yaml:"disabled" env:"USERLOG_EVENTS_DISABLED" desc:"Disables listening for events. Set this to true if the service should only handle HTTP requests." introductionVersion:"%%NEXT%%"` + Disabled bool `yaml:"disabled" env:"USERLOG_EVENTS_DISABLED" desc:"Disables listening for events. Set this to true if the service should only handle HTTP requests." introductionVersion:"9.1.0"` Endpoint string `yaml:"endpoint" env:"OC_EVENTS_ENDPOINT;USERLOG_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"1.0.0"` Cluster string `yaml:"cluster" env:"OC_EVENTS_CLUSTER;USERLOG_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Mandatory when using NATS as event system." introductionVersion:"1.0.0"` TLSInsecure bool `yaml:"tls_insecure" env:"OC_INSECURE;OC_EVENTS_TLS_INSECURE;USERLOG_EVENTS_TLS_INSECURE" desc:"Whether to verify the server TLS certificates." introductionVersion:"1.0.0"` @@ -73,7 +73,7 @@ type CORS struct { // HTTP defines the available http configuration. type HTTP struct { - Disabled bool `yaml:"disabled" env:"USERLOG_HTTP_DISABLED" desc:"Disables the HTTP service. Set this to true if the service should only handle events." introductionVersion:"%%NEXT%%"` + Disabled bool `yaml:"disabled" env:"USERLOG_HTTP_DISABLED" desc:"Disables the HTTP service. Set this to true if the service should only handle events." introductionVersion:"9.1.0"` Addr string `yaml:"addr" env:"USERLOG_HTTP_ADDR" desc:"The bind address of the HTTP service." introductionVersion:"1.0.0"` Namespace string `yaml:"-"` Root string `yaml:"root" env:"USERLOG_HTTP_ROOT" desc:"Subdirectory that serves as the root for this HTTP service." introductionVersion:"1.0.0"` diff --git a/services/web/pkg/theme/kv.go b/services/web/pkg/theme/kv.go index 928c7edb7a..33ae64cebe 100644 --- a/services/web/pkg/theme/kv.go +++ b/services/web/pkg/theme/kv.go @@ -6,18 +6,22 @@ import ( "strings" "dario.cat/mergo" + "github.com/mohae/deepcopy" "github.com/spf13/afero" ) // KV is a generic key-value map. type KV map[string]any -// MergeKV merges the given key-value maps. +// MergeKV merges the given key-value maps into a new one, the given maps are not modified. func MergeKV(values ...KV) (KV, error) { var kv KV for _, v := range values { - err := mergo.Merge(&kv, v, mergo.WithOverride) + // mergo reuses the nested maps of a source in the destination and merges later sources into them, + // so it must only see a copy; otherwise shared inputs like themeDefaults get modified, + // concurrently when requests run in parallel. + err := mergo.Merge(&kv, deepcopy.Copy(v).(KV), mergo.WithOverride) if err != nil { return nil, err } diff --git a/services/web/pkg/theme/kv_test.go b/services/web/pkg/theme/kv_test.go index 855da86ec7..18cec30f23 100644 --- a/services/web/pkg/theme/kv_test.go +++ b/services/web/pkg/theme/kv_test.go @@ -2,6 +2,8 @@ package theme_test import ( "encoding/json" + "strconv" + "sync" "testing" "github.com/spf13/afero" @@ -30,6 +32,95 @@ func TestMergeKV(t *testing.T) { }) } +func TestMergeKVDoesNotMutateInputs(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + } + override := theme.KV{ + "common": map[string]any{ + "logo": "override.svg", + "shareRoles": map[string]any{ + "viewer": map[string]any{"iconName": "glasses"}, + }, + }, + } + + result, err := theme.MergeKV(defaults, override) + assert.Nil(t, err) + assert.Equal(t, theme.KV{ + "common": theme.KV{ + "name": "default", + "logo": "override.svg", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "glasses"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + }, result) + + // the inputs must be left untouched by the merge + assert.Equal(t, theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + }, defaults) + + // changing the result must not leak back into the inputs + result["common"].(theme.KV)["name"] = "changed" + result["list"].([]any)[0].(theme.KV)["a"] = "changed" + assert.Equal(t, "default", defaults["common"].(theme.KV)["name"]) + assert.Equal(t, "a", defaults["list"].([]any)[0].(theme.KV)["a"]) + assert.Equal(t, "override.svg", override["common"].(map[string]any)["logo"]) + + // a later merge must not see values from an earlier one + result, err = theme.MergeKV(defaults, theme.KV{}) + assert.Nil(t, err) + assert.NotContains(t, result["common"], "logo") +} + +func TestMergeKVConcurrent(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + } + + var wg sync.WaitGroup + for i := range 50 { + wg.Add(1) + go func() { + defer wg.Done() + name := strconv.Itoa(i) + result, err := theme.MergeKV(defaults, theme.KV{ + "common": map[string]any{ + "name": name, + "shareRoles": map[string]any{ + "viewer": map[string]any{"iconName": name}, + }, + }, + }) + assert.Nil(t, err) + assert.Equal(t, name, result["common"].(theme.KV)["name"]) + }() + } + wg.Wait() + + assert.Equal(t, "default", defaults["common"].(theme.KV)["name"]) +} + func TestPatchKV(t *testing.T) { in := theme.KV{ "a": map[string]any{ diff --git a/services/web/pkg/theme/service_test.go b/services/web/pkg/theme/service_test.go index 91d858761d..70af28bbc7 100644 --- a/services/web/pkg/theme/service_test.go +++ b/services/web/pkg/theme/service_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "sync" "testing" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -72,3 +73,70 @@ func TestService_Get(t *testing.T) { // themeDefaults assert.Equal(t, jsonData.Get("common.shareRoles."+unifiedrole.UnifiedRoleViewerID+".name").String(), "UnifiedRoleViewer") } + +func TestService_GetConcurrent(t *testing.T) { + primaryFS := fsx.NewMemMapFs() + fallbackFS := fsx.NewFallbackFS(primaryFS, fsx.NewMemMapFs()) + + add := func(filename string, content any) { + b, err := json.Marshal(content) + assert.Nil(t, err) + + assert.Nil(t, afero.WriteFile(primaryFS, filename, b, 0644)) + } + + // the base themes overlap with the defaults, like the shipped theme.json does + add("a/theme.json", map[string]any{ + "common": map[string]any{ + "name": "a", + "logo": "a.svg", + "shareRoles": map[string]any{ + unifiedrole.UnifiedRoleViewerID: map[string]any{"iconName": "a"}, + }, + }, + }) + add("b/theme.json", map[string]any{ + "common": map[string]any{ + "name": "b", + }, + }) + add("_branding/theme.json", map[string]any{ + "common": map[string]any{ + "slogan": "branding", + }, + }) + + service, _ := theme.NewService( + theme.ServiceOptions{}. + WithThemeFS(fallbackFS). + WithGatewaySelector(mocks.NewSelectable[gateway.GatewayAPIClient](t)), + ) + + get := func(id string) gjson.Result { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.SetPathValue("id", id) + w := httptest.NewRecorder() + service.Get(w, r) + assert.Equal(t, http.StatusOK, w.Code) + return gjson.Parse(w.Body.String()) + } + + var wg sync.WaitGroup + for i := range 50 { + id := []string{"a", "b"}[i%2] + wg.Add(1) + go func() { + defer wg.Done() + jsonData := get(id) + assert.Equal(t, id, jsonData.Get("common.name").String()) + assert.Equal(t, "branding", jsonData.Get("common.slogan").String()) + }() + } + wg.Wait() + + // values of theme a must never leak into the defaults and therefore into theme b + jsonData := get("b") + assert.Equal(t, "b", jsonData.Get("common.name").String()) + assert.False(t, jsonData.Get("common.logo").Exists()) + assert.Equal(t, "eye", jsonData.Get("common.shareRoles."+unifiedrole.UnifiedRoleViewerID+".iconName").String()) +} diff --git a/vendor/github.com/go-chi/chi/v5/README.md b/vendor/github.com/go-chi/chi/v5/README.md index 07aeaa8011..5f9f443567 100644 --- a/vendor/github.com/go-chi/chi/v5/README.md +++ b/vendor/github.com/go-chi/chi/v5/README.md @@ -368,50 +368,50 @@ with `net/http` can be used with chi's mux. | [WithValue] | Short-hand middleware to set a key/value on the request context | ---------------------------------------------------------------------------------------------------- -[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentEncoding -[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentType -[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/middleware#BasicAuth -[Compress]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compress -[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ContentCharset -[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/middleware#CleanPath -[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetHead -[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetReqID -[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Heartbeat -[Logger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Logger -[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/middleware#NoCache -[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Profiler -[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromHeader -[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFF -[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFFTrustedProxies -[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromRemoteAddr -[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIP -[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIPAddr -[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RealIP -[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Recoverer -[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RedirectSlashes -[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestLogger -[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestID -[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RouteHeaders -[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#SetHeader -[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#StripSlashes +[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentEncoding +[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentType +[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#BasicAuth +[Compress]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compress +[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ContentCharset +[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#CleanPath +[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetHead +[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetReqID +[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Heartbeat +[Logger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Logger +[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#NoCache +[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Profiler +[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromHeader +[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFF +[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFFTrustedProxies +[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromRemoteAddr +[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIP +[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIPAddr +[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RealIP +[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Recoverer +[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RedirectSlashes +[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestLogger +[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestID +[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RouteHeaders +[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#SetHeader +[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#StripSlashes [Sunset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Sunset -[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Throttle -[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleBacklog -[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleWithOpts -[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Timeout -[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#URLFormat -[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithLogEntry -[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithValue -[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compressor -[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#DefaultLogFormatter -[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/middleware#EncoderFunc -[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRoute -[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRouter -[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogEntry -[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogFormatter -[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LoggerInterface -[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleOpts -[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WrapResponseWriter +[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Throttle +[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleBacklog +[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleWithOpts +[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Timeout +[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#URLFormat +[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithLogEntry +[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithValue +[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compressor +[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#DefaultLogFormatter +[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#EncoderFunc +[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRoute +[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRouter +[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogEntry +[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogFormatter +[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LoggerInterface +[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleOpts +[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WrapResponseWriter ### Choosing a ClientIP middleware diff --git a/vendor/github.com/go-chi/chi/v5/chi.go b/vendor/github.com/go-chi/chi/v5/chi.go index cb129e3054..6911bb5511 100644 --- a/vendor/github.com/go-chi/chi/v5/chi.go +++ b/vendor/github.com/go-chi/chi/v5/chi.go @@ -2,7 +2,7 @@ // // chi supports the four most recent major versions of Go. // -// Example: +// # Example // // package main // @@ -25,11 +25,13 @@ // http.ListenAndServe(":3333", r) // } // -// See github.com/go-chi/chi/_examples/ for more in-depth examples. +// See [github.com/go-chi/chi/v5/_examples] for more in-depth examples. +// +// # URL patterns // // URL patterns allow for easy matching of path components in HTTP // requests. The matching components can then be accessed using -// chi.URLParam(). All patterns must begin with a slash. +// [chi.URLParam](). All patterns must begin with a slash. // // A simple named placeholder {name} matches any sequence of characters // up to the next / or the end of the URL. Trailing slashes on paths must @@ -37,11 +39,11 @@ // // A placeholder with a name followed by a colon allows a regular // expression match, for example {number:\\d+}. The regular expression -// syntax is Go's normal regexp RE2 syntax, except that / will never be -// matched. An anonymous regexp pattern is allowed, using an empty string -// before the colon in the placeholder, such as {:\\d+} +// syntax is Go's normal [regexp] RE2 syntax (see [regexp/syntax]), except +// that / will never be matched. An anonymous regexp pattern is allowed, using +// an empty string before the colon in the placeholder, such as {:\\d+}. // -// The special placeholder of asterisk matches the rest of the requested +// The special placeholder of asterisk (*) matches the rest of the requested // URL. Any trailing characters in the pattern are ignored. This is the only // placeholder which will match / characters. // diff --git a/vendor/github.com/go-chi/chi/v5/context.go b/vendor/github.com/go-chi/chi/v5/context.go index 82220730e9..c5c9a7432a 100644 --- a/vendor/github.com/go-chi/chi/v5/context.go +++ b/vendor/github.com/go-chi/chi/v5/context.go @@ -3,15 +3,13 @@ package chi import ( "context" "net/http" + "slices" "strings" ) // URLParam returns the url parameter from a http.Request object. func URLParam(r *http.Request, key string) string { - if rctx := RouteContext(r.Context()); rctx != nil { - return rctx.URLParam(key) - } - return "" + return URLParamFromCtx(r.Context(), key) } // URLParamFromCtx returns the url parameter from a http.Request Context. @@ -42,6 +40,8 @@ var ( // Context is the default routing context set on the root node of a // request context to track route patterns, URL parameters and // an optional routing path. +// +// NOTE: New reference fields (slices, maps, pointers) must be deep-copied in Clone. type Context struct { Routes Routes @@ -95,12 +95,36 @@ func (x *Context) Reset() { x.parentCtx = nil } +// Clone a routing context so that it may be used outside of the request/response +// lifecycle, e.g. in a goroutine that outlives the request handler. +// +// Clone must be called before the request handler returns; after that, the +// original context is reset and put back into the pool for reuse by another +// request, racing with the copy. +func (x *Context) Clone() *Context { + clone := *x + + // Detach from the request's context, which is canceled once the request finishes. + clone.parentCtx = nil + + clone.URLParams.Keys = slices.Clone(x.URLParams.Keys) + clone.URLParams.Values = slices.Clone(x.URLParams.Values) + + clone.routeParams.Keys = slices.Clone(x.routeParams.Keys) + clone.routeParams.Values = slices.Clone(x.routeParams.Values) + + clone.RoutePatterns = slices.Clone(x.RoutePatterns) + clone.methodsAllowed = slices.Clone(x.methodsAllowed) + + return &clone +} + // URLParam returns the corresponding URL parameter value from the request // routing context. func (x *Context) URLParam(key string) string { - for k := len(x.URLParams.Keys) - 1; k >= 0; k-- { - if x.URLParams.Keys[k] == key { - return x.URLParams.Values[k] + for i, k := range slices.Backward(x.URLParams.Keys) { + if k == key { + return x.URLParams.Values[i] } } return "" diff --git a/vendor/github.com/go-chi/chi/v5/middleware/client_ip.go b/vendor/github.com/go-chi/chi/v5/middleware/client_ip.go index 7e1be57b08..55e2dc25d2 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/client_ip.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/client_ip.go @@ -5,6 +5,7 @@ import ( "net" "net/http" "net/netip" + "slices" "strings" ) @@ -38,15 +39,37 @@ const xForwardedForHeader = "X-Forwarded-For" // // v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are // stripped before storage. -func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler { +// +// Overwriting only protects requests that pass through your proxy. A client +// that reaches this server directly can set the header to anything. Pass +// your proxy's CIDR prefixes as trustedIPPrefixes to close that gap: the +// header is then read only when r.RemoteAddr falls within one of them; +// otherwise r.RemoteAddr itself is the client IP. This mirrors nginx +// (set_real_ip_from), Apache (RemoteIPTrustedProxy), and Caddy +// (trusted_proxies), and Cloudflare's advice to accept origin traffic only +// from its IP ranges. Without trustedIPPrefixes, guarantee at the network +// layer (security group / firewall) that only your proxy can reach this +// server. +// +// r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP", +// "173.245.48.0/20", // Cloudflare IPv4, see https://www.cloudflare.com/ips/ +// "2400:cb00::/32", // Cloudflare IPv6 +// )) +// +// Panics at startup if any prefix is invalid. +func ClientIPFromHeader(trustedHeader string, trustedIPPrefixes ...string) func(http.Handler) http.Handler { header := http.CanonicalHeaderKey(trustedHeader) + prefixes := mustParsePrefixes(trustedIPPrefixes) return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - values := r.Header.Values(header) - if len(values) > 0 { - if ip, ok := parseHeaderAddr(values[len(values)-1]); ok { - r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip)) - } + var found netip.Addr + if peer, untrusted := untrustedPeer(r, prefixes); untrusted { + found = peer + } else if values := r.Header.Values(header); len(values) > 0 { + found, _ = parseHeaderAddr(values[len(values)-1]) + } + if found.IsValid() { + r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found)) } h.ServeHTTP(w, r) }) @@ -77,9 +100,15 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler { // "2600:9000::/28", // CloudFront IPv6 // )) // -// Calling with no arguments returns the rightmost XFF entry, or no IP if -// that entry doesn't parse (fail-closed) — safe only if you have exactly -// one trusted hop directly in front of this server (e.g., nginx on localhost). +// The TCP peer in r.RemoteAddr is treated as the rightmost hop: if it is +// not within a trusted prefix, it is the client IP and X-Forwarded-For is +// ignored. A client reaching this server directly therefore cannot spoof +// its IP. If r.RemoteAddr doesn't parse, no client IP is set (fail-closed). +// +// At least one prefix is required. For a single trusted hop directly in +// front of this server (e.g., nginx on localhost), pass its address: +// +// r.Use(middleware.ClientIPFromXFF("127.0.0.1/32", "::1/128")) // // v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are // stripped before the prefix check and storage; otherwise an attacker @@ -88,26 +117,30 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler { // If you know the number of trusted proxies but not their IPs, use // [ClientIPFromXFFTrustedProxies] instead. // -// Panics at startup if any prefix is invalid. +// Panics at startup if no prefix is given or any prefix is invalid. func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handler { - prefixes := make([]netip.Prefix, len(trustedIPPrefixes)) - for i, p := range trustedIPPrefixes { - prefixes[i] = netip.MustParsePrefix(p) + if len(trustedIPPrefixes) == 0 { + panic("middleware.ClientIPFromXFF: at least one trusted IP prefix is required; use ClientIPFromXFFTrustedProxies(1) to trust any peer") } + prefixes := mustParsePrefixes(trustedIPPrefixes) return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var found netip.Addr - walkXFF(r.Header[xForwardedForHeader], func(v string) bool { - ip, ok := parseHeaderAddr(v) - if !ok { - return true // fail-closed; leave found unset - } - if inAnyPrefix(ip, prefixes) { - return false // trusted hop; keep walking left - } - found = ip - return true - }) + if peer, untrusted := untrustedPeer(r, prefixes); untrusted { + found = peer + } else { + walkXFF(r.Header[xForwardedForHeader], func(v string) bool { + ip, ok := parseHeaderAddr(v) + if !ok { + return true // fail-closed; leave found unset + } + if inAnyPrefix(ip, prefixes) { + return false // trusted hop; keep walking left + } + found = ip + return true + }) + } if found.IsValid() { r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found)) } @@ -186,12 +219,8 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt // IPv6 zones are preserved (link-local connections may legitimately have one). func ClientIPFromRemoteAddr(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - host, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - host = r.RemoteAddr // RemoteAddr may already be a bare IP (e.g. in tests). - } - if ip, err := netip.ParseAddr(host); err == nil { - r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip.Unmap())) + if ip, ok := parseRemoteAddr(r.RemoteAddr); ok { + r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip)) } h.ServeHTTP(w, r) }) @@ -226,8 +255,7 @@ func GetClientIPAddr(ctx context.Context) netip.Addr { // comma-separated entries in order received — so an attacker cannot pick // which value security logic sees by sending a duplicate header. func walkXFF(headers []string, visit func(entry string) bool) { - for hi := len(headers) - 1; hi >= 0; hi-- { - h := headers[hi] + for _, h := range slices.Backward(headers) { for h != "" { var v string if i := strings.LastIndexByte(h, ','); i >= 0 { @@ -246,6 +274,45 @@ func walkXFF(headers []string, visit func(entry string) bool) { } } +// mustParsePrefixes parses CIDR prefixes, panicking on the first invalid one. +func mustParsePrefixes(cidrs []string) []netip.Prefix { + prefixes := make([]netip.Prefix, len(cidrs)) + for i, p := range cidrs { + prefixes[i] = netip.MustParsePrefix(p) + } + return prefixes +} + +// untrustedPeer reports whether the TCP peer in r.RemoteAddr is outside +// prefixes. If so, peer is the client IP, or invalid if RemoteAddr doesn't +// parse. With no prefixes, every peer is trusted. +func untrustedPeer(r *http.Request, prefixes []netip.Prefix) (peer netip.Addr, untrusted bool) { + if len(prefixes) == 0 { + return netip.Addr{}, false + } + peer, ok := parseRemoteAddr(r.RemoteAddr) + if !ok { + return netip.Addr{}, true + } + // Zoned addresses never match a prefix, so check a link-local peer without its zone. + return peer, !inAnyPrefix(peer.WithZone(""), prefixes) +} + +// parseRemoteAddr parses the host of r.RemoteAddr. v4-mapped IPv6 folds to +// plain v4; the IPv6 zone is preserved (link-local connections may +// legitimately have one). +func parseRemoteAddr(remoteAddr string) (netip.Addr, bool) { + host, _, err := net.SplitHostPort(remoteAddr) + if err != nil { + host = remoteAddr // RemoteAddr may already be a bare IP (e.g. in tests). + } + ip, err := netip.ParseAddr(host) + if err != nil { + return netip.Addr{}, false + } + return ip.Unmap(), true +} + // inAnyPrefix reports whether ip falls within any of the given prefixes. func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool { for _, p := range prefixes { @@ -263,7 +330,7 @@ func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool { // address, so without folding/stripping an attacker could escape an // otherwise valid trust list. // -// Header-sourced IPs only. [ClientIPFromRemoteAddr] normalizes inline +// Header-sourced IPs only. r.RemoteAddr goes through parseRemoteAddr // (Unmap, but zone preserved for legitimate link-local connections). func parseHeaderAddr(s string) (netip.Addr, bool) { ip, err := netip.ParseAddr(s) diff --git a/vendor/github.com/go-chi/chi/v5/middleware/compress.go b/vendor/github.com/go-chi/chi/v5/middleware/compress.go index d4a26b38d3..2b3653f23a 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/compress.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/compress.go @@ -148,13 +148,21 @@ func NewCompressor(level int, types ...string) *Compressor { // // For example, add the Brotli algorithm: // -// import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc" +// import "github.com/google/brotli/go/cbrotli" // // compressor := middleware.NewCompressor(5, "text/html") // compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer { -// params := brotli_enc.NewBrotliParams() -// params.SetQuality(level) -// return brotli_enc.NewBrotliWriter(params, w) +// return cbrotli.NewWriter(w, cbrotli.WriterOptions{Quality: level}) +// }) +// +// Alternatively, this Cgo-free Brotli module can be used: +// +// import "github.com/andybalholm/brotli" +// +// compressor := middleware.NewCompressor(5, "text/html") +// +// compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer { +// return brotli.NewWriterV2(w, level) // }) func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) { encoding = strings.ToLower(encoding) @@ -174,7 +182,7 @@ func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) { encoder := fn(io.Discard, c.level) if _, ok := encoder.(ioResetterWriter); ok { pool := &sync.Pool{ - New: func() interface{} { + New: func() any { return fn(io.Discard, c.level) }, } diff --git a/vendor/github.com/go-chi/chi/v5/middleware/content_charset.go b/vendor/github.com/go-chi/chi/v5/middleware/content_charset.go index 8e75fe8e46..55773517cb 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/content_charset.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/content_charset.go @@ -8,6 +8,7 @@ import ( // ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match. // An empty charset will allow requests with no Content-Type header or no specified charset. +// Requests without a body (ContentLength == 0) are always allowed. func ContentCharset(charsets ...string) func(next http.Handler) http.Handler { for i, c := range charsets { charsets[i] = strings.ToLower(c) @@ -15,6 +16,11 @@ func ContentCharset(charsets ...string) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ContentLength == 0 { + next.ServeHTTP(w, r) + return + } + if !contentEncoding(r.Header.Get("Content-Type"), charsets...) { w.WriteHeader(http.StatusUnsupportedMediaType) return diff --git a/vendor/github.com/go-chi/chi/v5/middleware/logger.go b/vendor/github.com/go-chi/chi/v5/middleware/logger.go index ba5391f64a..72e735fe45 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/logger.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/logger.go @@ -67,8 +67,8 @@ type LogFormatter interface { // LogEntry records the final log when a request completes. // See defaultLogEntry for an example implementation. type LogEntry interface { - Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) - Panic(v interface{}, stack []byte) + Write(status, bytes int, header http.Header, elapsed time.Duration, extra any) + Panic(v any, stack []byte) } // GetLogEntry returns the in-context LogEntry for a request. @@ -85,7 +85,7 @@ func WithLogEntry(r *http.Request, entry LogEntry) *http.Request { // LoggerInterface accepts printing to stdlib logger or compatible logger. type LoggerInterface interface { - Print(v ...interface{}) + Print(v ...any) } // DefaultLogFormatter is a simple logger that implements a LogFormatter. @@ -137,7 +137,7 @@ type defaultLogEntry struct { useColor bool } -func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) { +func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra any) { switch { case status < 200: cW(l.buf, l.useColor, bBlue, "%03d", status) @@ -165,7 +165,7 @@ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed t l.Logger.Print(l.buf.String()) } -func (l *defaultLogEntry) Panic(v interface{}, stack []byte) { +func (l *defaultLogEntry) Panic(v any, stack []byte) { printPrettyStack(v, l.useColor) } diff --git a/vendor/github.com/go-chi/chi/v5/middleware/recoverer.go b/vendor/github.com/go-chi/chi/v5/middleware/recoverer.go index ba77de74fb..e82de6b685 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/recoverer.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/recoverer.go @@ -51,14 +51,14 @@ func Recoverer(next http.Handler) http.Handler { // for ability to test the PrintPrettyStack function var recovererErrorWriter io.Writer = os.Stderr -func PrintPrettyStack(rvr interface{}) { +func PrintPrettyStack(rvr any) { printPrettyStack(rvr, true) } // printPrettyStack prints a formatted stack trace to stderr. When useColor is // false, ANSI colour codes are suppressed, which is useful for terminals that // do not support them (e.g. on Windows) or when output is being captured. -func printPrettyStack(rvr interface{}, useColor bool) { +func printPrettyStack(rvr any, useColor bool) { debugStack := debug.Stack() s := prettyStack{} out, err := s.parse(debugStack, rvr, useColor) @@ -73,7 +73,7 @@ func printPrettyStack(rvr interface{}, useColor bool) { type prettyStack struct { } -func (s prettyStack) parse(debugStack []byte, rvr interface{}, useColor bool) ([]byte, error) { +func (s prettyStack) parse(debugStack []byte, rvr any, useColor bool) ([]byte, error) { var err error buf := &bytes.Buffer{} diff --git a/vendor/github.com/go-chi/chi/v5/middleware/terminal.go b/vendor/github.com/go-chi/chi/v5/middleware/terminal.go index 5ead7b9243..5613318cda 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/terminal.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/terminal.go @@ -52,7 +52,7 @@ func init() { } // colorWrite -func cW(w io.Writer, useColor bool, color []byte, s string, args ...interface{}) { +func cW(w io.Writer, useColor bool, color []byte, s string, args ...any) { if IsTTY && useColor { w.Write(color) } diff --git a/vendor/github.com/go-chi/chi/v5/middleware/value.go b/vendor/github.com/go-chi/chi/v5/middleware/value.go index a9dfd4345d..fbb9573e1f 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/value.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/value.go @@ -6,7 +6,7 @@ import ( ) // WithValue is a middleware that sets a given key/value in a context chain. -func WithValue(key, val interface{}) func(next http.Handler) http.Handler { +func WithValue(key, val any) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { r = r.WithContext(context.WithValue(r.Context(), key, val)) diff --git a/vendor/github.com/go-chi/chi/v5/middleware/wrap_writer.go b/vendor/github.com/go-chi/chi/v5/middleware/wrap_writer.go index 936ce7e803..2fdd9c44e3 100644 --- a/vendor/github.com/go-chi/chi/v5/middleware/wrap_writer.go +++ b/vendor/github.com/go-chi/chi/v5/middleware/wrap_writer.go @@ -63,6 +63,7 @@ type WrapResponseWriter interface { Unwrap() http.ResponseWriter // Discard causes all writes to the original ResponseWriter be discarded, // instead writing only to the tee'd writer if it's set. + // Flush calls also do not reach the original ResponseWriter. // The caller is responsible for calling WriteHeader and Write on the // original ResponseWriter once the processing is done. Discard() @@ -119,6 +120,13 @@ func (b *basicWriter) maybeWriteHeader() { } } +func (b *basicWriter) flush() { + b.maybeWriteHeader() + if !b.discard { + b.ResponseWriter.(http.Flusher).Flush() + } +} + func (b *basicWriter) Status() int { return b.code } @@ -145,9 +153,7 @@ type flushWriter struct { } func (f *flushWriter) Flush() { - f.wroteHeader = true - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() + f.basicWriter.flush() } var _ http.Flusher = &flushWriter{} @@ -170,9 +176,7 @@ type flushHijackWriter struct { } func (f *flushHijackWriter) Flush() { - f.wroteHeader = true - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() + f.basicWriter.flush() } func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { @@ -192,9 +196,7 @@ type httpFancyWriter struct { } func (f *httpFancyWriter) Flush() { - f.wroteHeader = true - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() + f.basicWriter.flush() } func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { @@ -237,9 +239,7 @@ type http2FancyWriter struct { } func (f *http2FancyWriter) Flush() { - f.wroteHeader = true - fl := f.basicWriter.ResponseWriter.(http.Flusher) - fl.Flush() + f.basicWriter.flush() } var _ http.Flusher = &http2FancyWriter{} diff --git a/vendor/github.com/go-chi/chi/v5/mux.go b/vendor/github.com/go-chi/chi/v5/mux.go index 37cd50043f..7cfc6143d6 100644 --- a/vendor/github.com/go-chi/chi/v5/mux.go +++ b/vendor/github.com/go-chi/chi/v5/mux.go @@ -51,7 +51,7 @@ type Mux struct { // interface. func NewMux() *Mux { mux := &Mux{tree: &node{}, pool: &sync.Pool{}} - mux.pool.New = func() interface{} { + mux.pool.New = func() any { return NewRouteContext() } return mux @@ -305,6 +305,14 @@ func (mx *Mux) Mount(pattern string, handler http.Handler) { // Assign sub-Router's with the parent not found & method not allowed handler if not specified. subr, ok := handler.(*Mux) + + // Provide runtime safety for ensuring a router isn't mounted onto itself, + // which includes an inline mux derived from it via With()/Group() since + // that shares the same underlying tree. See issue #843. + if ok && subr.tree == mx.tree { + panic(fmt.Sprintf("chi: attempting to Mount() a router onto itself on '%s'", pattern)) + } + if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil { subr.NotFound(mx.notFoundHandler) } diff --git a/vendor/github.com/go-chi/chi/v5/tree.go b/vendor/github.com/go-chi/chi/v5/tree.go index e7bc9ed080..af4052c8c0 100644 --- a/vendor/github.com/go-chi/chi/v5/tree.go +++ b/vendor/github.com/go-chi/chi/v5/tree.go @@ -839,8 +839,8 @@ func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label } // tailSort pushes nodes with '/' as the tail to the end of the list for param nodes. // The list order determines the traversal order. func (ns nodes) tailSort() { - for i := len(ns) - 1; i >= 0; i-- { - if ns[i].typ > ntStatic && ns[i].tail == '/' { + for i, n := range slices.Backward(ns) { + if n.typ > ntStatic && n.tail == '/' { ns.Swap(i, len(ns)-1) return } diff --git a/vendor/github.com/go-jose/go-jose/v4/crypter.go b/vendor/github.com/go-jose/go-jose/v4/crypter.go index e3df79c2dc..53636c57b3 100644 --- a/vendor/github.com/go-jose/go-jose/v4/crypter.go +++ b/vendor/github.com/go-jose/go-jose/v4/crypter.go @@ -428,6 +428,13 @@ func (ctx *genericEncrypter) Options() EncrypterOptions { } } +func validateContentEncryptionKeySize(cek []byte, cipher contentCipher) error { + if len(cek) != cipher.keySize() { + return ErrInvalidKeySize + } + return nil +} + // Decrypt and validate the object and return the plaintext. This // function does not support multi-recipient. If you desire multi-recipient // decryption use DecryptMulti instead. @@ -495,6 +502,10 @@ func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error) if err != nil { return nil, ErrCryptoFailure } + err = validateContentEncryptionKeySize(cek, cipher) + if err != nil { + return nil, ErrCryptoFailure + } // Found a valid CEK -- let's try to decrypt. plaintext, err = cipher.decrypt(cek, authData, parts) @@ -572,6 +583,10 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade if err != nil { continue } + err = validateContentEncryptionKeySize(cek, cipher) + if err != nil { + continue + } // Found a valid CEK -- let's try to decrypt. plaintext, err = cipher.decrypt(cek, authData, parts) diff --git a/vendor/github.com/go-jose/go-jose/v4/jwe.go b/vendor/github.com/go-jose/go-jose/v4/jwe.go index ae173461b7..a516901078 100644 --- a/vendor/github.com/go-jose/go-jose/v4/jwe.go +++ b/vendor/github.com/go-jose/go-jose/v4/jwe.go @@ -202,15 +202,6 @@ func (parsed *rawJSONWebEncryption) sanitized( } } - // Note: this must be called _after_ we parse the protected header, - // otherwise fields from the protected header will not get picked up. - var err error - mergedHeaders := obj.mergedHeaders(nil) - obj.Header, err = mergedHeaders.sanitized() - if err != nil { - return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders) - } - if len(parsed.Recipients) == 0 { obj.recipients = []recipientInfo{ { @@ -264,6 +255,15 @@ func (parsed *rawJSONWebEncryption) sanitized( } } + // Note: this must be called _after_ we parse the protected header, + // otherwise fields from the protected header will not get picked up. + mergedHeaders := obj.mergedHeaders(nil) + var err error + obj.Header, err = mergedHeaders.sanitized() + if err != nil { + return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %w", err) + } + obj.iv = parsed.Iv.bytes() obj.ciphertext = parsed.Ciphertext.bytes() obj.tag = parsed.Tag.bytes() diff --git a/vendor/github.com/go-jose/go-jose/v4/jwk.go b/vendor/github.com/go-jose/go-jose/v4/jwk.go index f712ec7ec8..8b7aa05ec2 100644 --- a/vendor/github.com/go-jose/go-jose/v4/jwk.go +++ b/vendor/github.com/go-jose/go-jose/v4/jwk.go @@ -177,13 +177,29 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) { // UnmarshalJSON reads a key from its JSON representation. // // Returns ErrUnsupportedKeyType for unrecognized or unsupported "kty" header values. -func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) { +// +// Directly unmarshaling a JWK is not safe for untrusted input. +func (k *JSONWebKey) UnmarshalJSON(data []byte) error { + return k.unmarshalJSON(data, true) +} + +// unmarshalJSON reads a key from its JSON representation. +// +// If allowPrivate is false, a JWK with private key material is rejected and the +// function is safe for use against untrusted input. +func (k *JSONWebKey) unmarshalJSON(data []byte, allowPrivate bool) (err error) { var raw rawJSONWebKey err = json.Unmarshal(data, &raw) if err != nil { return err } + if !allowPrivate && + (raw.K != nil || raw.D != nil || raw.P != nil || raw.Q != nil || + raw.Dp != nil || raw.Dq != nil || raw.Qi != nil) { + return errors.New("go-jose/go-jose: JWK contains private parameters") + } + certs, err := parseCertificateChain(raw.X5c) if err != nil { return fmt.Errorf("go-jose/go-jose: failed to unmarshal x5c field: %s", err) @@ -505,13 +521,25 @@ func (k *JSONWebKey) Valid() bool { return true } +// MaxRSAModulusBits is the largest RSA modulus size, in bits, that will be +// accepted when parsing a JWK. Applications that need larger keys can raise +// this limit. +// +// If modifying MaxRSAModulusBits, do it before any parsing occurs. +var MaxRSAModulusBits = 4096 + func (key rawJSONWebKey) rsaPublicKey() (*rsa.PublicKey, error) { if key.N == nil || key.E == nil { return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, missing n/e values") } + n := key.N.bigInt() + if n.BitLen() > MaxRSAModulusBits { + return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large") + } + return &rsa.PublicKey{ - N: key.N.bigInt(), + N: n, E: key.E.toInt(), }, nil } @@ -673,16 +701,23 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) { return nil, fmt.Errorf("go-jose/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", ")) } + n := key.N.bigInt() + if n.BitLen() > MaxRSAModulusBits { + return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large") + } + + p, q := key.P.bigInt(), key.Q.bigInt() + if p.BitLen()+q.BitLen() > n.BitLen()+1 || new(big.Int).Mul(p, q).Cmp(n) != 0 { + return nil, errors.New("go-jose/go-jose: invalid RSA private key, p * q != n") + } + rv := &rsa.PrivateKey{ PublicKey: rsa.PublicKey{ - N: key.N.bigInt(), + N: n, E: key.E.toInt(), }, - D: key.D.bigInt(), - Primes: []*big.Int{ - key.P.bigInt(), - key.Q.bigInt(), - }, + D: key.D.bigInt(), + Primes: []*big.Int{p, q}, } if key.Dp != nil { diff --git a/vendor/github.com/go-jose/go-jose/v4/jws.go b/vendor/github.com/go-jose/go-jose/v4/jws.go index 0444a5da05..18224df7d9 100644 --- a/vendor/github.com/go-jose/go-jose/v4/jws.go +++ b/vendor/github.com/go-jose/go-jose/v4/jws.go @@ -275,17 +275,18 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo Signature: parsed.Signature, } - var err error - signature.Header, err = signature.mergedHeaders().sanitized() - if err != nil { - return nil, err - } - - alg := SignatureAlgorithm(signature.Header.Algorithm) + mergedHeaders := signature.mergedHeaders() + alg := mergedHeaders.getSignatureAlgorithm() if !containsSignatureAlgorithm(signatureAlgorithms, alg) { return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms) } + var err error + signature.Header, err = mergedHeaders.sanitized() + if err != nil { + return nil, err + } + if signature.header != nil { signature.Unprotected, err = signature.header.sanitized() if err != nil { @@ -323,17 +324,20 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo return nil, ErrUnprotectedNonce } - var err error - obj.Signatures[i].Header, err = obj.Signatures[i].mergedHeaders().sanitized() - if err != nil { - return nil, err - } + obj.Signatures[i].header = sig.Header - alg := SignatureAlgorithm(obj.Signatures[i].Header.Algorithm) + mergedHeaders := obj.Signatures[i].mergedHeaders() + alg := mergedHeaders.getSignatureAlgorithm() if !containsSignatureAlgorithm(signatureAlgorithms, alg) { return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms) } + var err error + obj.Signatures[i].Header, err = mergedHeaders.sanitized() + if err != nil { + return nil, err + } + if obj.Signatures[i].header != nil { obj.Signatures[i].Unprotected, err = obj.Signatures[i].header.sanitized() if err != nil { @@ -359,7 +363,6 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo // Copy value of sig original := sig - obj.Signatures[i].header = sig.Header obj.Signatures[i].original = &original } diff --git a/vendor/github.com/go-jose/go-jose/v4/shared.go b/vendor/github.com/go-jose/go-jose/v4/shared.go index 3df242ca6a..1e8bf88210 100644 --- a/vendor/github.com/go-jose/go-jose/v4/shared.go +++ b/vendor/github.com/go-jose/go-jose/v4/shared.go @@ -297,9 +297,10 @@ func (parsed rawHeader) getEPK() (*JSONWebKey, error) { if v == nil { return nil, nil } - var epk *JSONWebKey - err := json.Unmarshal(*v, &epk) - if err != nil { + // RFC 7518 Section 4.6.1.1: the "epk" header is the ephemeral public key + // of the originator. Reject private key material before parsing it. + epk := new(JSONWebKey) + if err := epk.unmarshalJSON(*v, false); err != nil { return nil, err } return epk, nil @@ -325,20 +326,6 @@ func (parsed rawHeader) getTag() (*byteBuffer, error) { return parsed.getByteBuffer(headerTag) } -// getJWK extracts parsed "jwk" from the raw JSON. -func (parsed rawHeader) getJWK() (*JSONWebKey, error) { - v := parsed[headerJWK] - if v == nil { - return nil, nil - } - var jwk *JSONWebKey - err := json.Unmarshal(*v, &jwk) - if err != nil { - return nil, err - } - return jwk, nil -} - // getCritical extracts parsed "crit" from the raw JSON. If omitted, it // returns an empty slice. func (parsed rawHeader) getCritical() ([]string, error) { @@ -424,10 +411,14 @@ func (parsed rawHeader) sanitized() (h Header, err error) { } switch k { case headerJWK: - var jwk *JSONWebKey - err = json.Unmarshal(*v, &jwk) + // RFC 7515 Section 4.1.3 and RFC 7516 Section 4.1.5: the "jwk" + // header is the public key that corresponds to the key used to + // sign the JWS or encrypt the JWE. Reject private key material + // before parsing it. + jwk := new(JSONWebKey) + err = jwk.unmarshalJSON(*v, false) if err != nil { - err = fmt.Errorf("failed to unmarshal JWK: %v: %#v", err, string(*v)) + err = fmt.Errorf("failed to unmarshal JWK: %w", err) return } h.JSONWebKey = jwk diff --git a/vendor/github.com/go-jose/go-jose/v4/tests.Containerfile b/vendor/github.com/go-jose/go-jose/v4/tests.Containerfile new file mode 100644 index 0000000000..b45da99bd2 --- /dev/null +++ b/vendor/github.com/go-jose/go-jose/v4/tests.Containerfile @@ -0,0 +1,13 @@ +# This containerfile can be used to run the go-jose tests and cli + +FROM golang:1.27-trixie +ENV GOTOOLCHAIN=local + +COPY . /src +WORKDIR /src + +# Install the jose-util cli, which will also build the library +RUN go build -o /usr/local/bin/jose-util ./jose-util + +# By default, run the tests +CMD ["go", "test", "./..."] diff --git a/vendor/github.com/go-jose/go-jose/v4/threat_model.md b/vendor/github.com/go-jose/go-jose/v4/threat_model.md new file mode 100644 index 0000000000..c9e66d4c20 --- /dev/null +++ b/vendor/github.com/go-jose/go-jose/v4/threat_model.md @@ -0,0 +1,25 @@ +# Threat model + +## What this project does and where untrusted input enters +go-jose is a Go implementation of JOSE family of algorithms. + +It is a library which will parse attacker-controlled data in network-reachable +services. + +## Components that matter most / least +The primary attack surface of interest is parsing and validating JWS, JWE, JWK, +etc when this library is used to implement authentication and authorization. + +## How to exercise it +Testing is primarily done by Golang unit tests, which can be run with the +tests.Container file's default CMD. + +## How you rate severity +Any authentication bypass enabled by a go-jose issue is a high+ severity. + +Denial-of-service attacks are of interest when the functions may be used in a protocol like OIDC, ACME, etc +which could have a server processing attacker-controlled data. + +## Anything to leave alone +Any bug which only affects the jose-util CLI tool, but it can be used to exercise the library. + diff --git a/vendor/github.com/go-playground/locales/README.md b/vendor/github.com/go-playground/locales/README.md index 7b6be2c647..ee6fa0e921 100644 --- a/vendor/github.com/go-playground/locales/README.md +++ b/vendor/github.com/go-playground/locales/README.md @@ -139,11 +139,13 @@ func main() { fmt.Println(l.CardinalPluralRule(1.0, 1)) fmt.Println(l.CardinalPluralRule(3, 0)) - // Ordinal Plural Rules - fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st - fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd - fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd - fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th + // Ordinal Plural Rules. The method returns the locales/plurals.Rule + // (e.g. One, Two, Few, Other) for the number; converting that rule into + // the actual suffix ("st", "nd", "rd", "th") is left to the caller. + fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st") + fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd") + fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd") + fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th") // Range Plural Rules fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 diff --git a/vendor/github.com/go-playground/locales/en/en.go b/vendor/github.com/go-playground/locales/en/en.go index baf343d4ff..6aa88f7ba9 100644 --- a/vendor/github.com/go-playground/locales/en/en.go +++ b/vendor/github.com/go-playground/locales/en/en.go @@ -498,10 +498,9 @@ func (en *en) FmtTimeShort(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -528,10 +527,9 @@ func (en *en) FmtTimeMedium(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -565,10 +563,9 @@ func (en *en) FmtTimeLong(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -607,10 +604,9 @@ func (en *en) FmtTimeFull(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) diff --git a/vendor/github.com/go-playground/locales/rules.go b/vendor/github.com/go-playground/locales/rules.go index 9202900149..6481269e36 100644 --- a/vendor/github.com/go-playground/locales/rules.go +++ b/vendor/github.com/go-playground/locales/rules.go @@ -98,7 +98,7 @@ type Translator interface { // returns the locales narrow weekday given the 'weekday' provided WeekdayNarrow(weekday time.Weekday) string - // WeekdaysNarrowreturns the locales narrow weekdays + // WeekdaysNarrow returns the locales narrow weekdays WeekdaysNarrow() []string // returns the locales short weekday given the 'weekday' provided @@ -113,7 +113,7 @@ type Translator interface { // returns the locales wide weekdays WeekdaysWide() []string - // The following Functions are common Formatting functionsfor the Translator's Locale + // The following Functions are common Formatting functions for the Translator's Locale // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' FmtNumber(num float64, v uint64) string @@ -228,14 +228,14 @@ func W(n float64, v uint64) (w int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then w will be zero + // will either be '0' or '0.xxxx', so if 1 then w will be zero // otherwise need to parse if len(s) != 1 { s = s[2:] - end := len(s) + 1 + end := 0 - for i := end; i >= 0; i-- { + for i := len(s) - 1; i >= 0; i-- { if s[i] != '0' { end = i + 1 break @@ -253,7 +253,7 @@ func F(n float64, v uint64) (f int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then f will be zero + // will either be '0' or '0.xxxx', so if 1 then f will be zero // otherwise need to parse if len(s) != 1 { @@ -270,14 +270,14 @@ func T(n float64, v uint64) (t int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then t will be zero + // will either be '0' or '0.xxxx', so if 1 then t will be zero // otherwise need to parse if len(s) != 1 { s = s[2:] - end := len(s) + 1 + end := 0 - for i := end; i >= 0; i-- { + for i := len(s) - 1; i >= 0; i-- { if s[i] != '0' { end = i + 1 break @@ -286,8 +286,11 @@ func T(n float64, v uint64) (t int64) { // ignoring error, because it can't fail as we generated // the string internally from a real number - t, _ = strconv.ParseInt(s[:end], 10, 64) + if end > 0 { + t, _ = strconv.ParseInt(s[:end], 10, 64) + } } return } + diff --git a/vendor/github.com/go-playground/validator/v10/.gitignore b/vendor/github.com/go-playground/validator/v10/.gitignore index 347072e38a..087a2ea52e 100644 --- a/vendor/github.com/go-playground/validator/v10/.gitignore +++ b/vendor/github.com/go-playground/validator/v10/.gitignore @@ -7,6 +7,8 @@ _obj _test bin +.gocache/ +.gomodcache/ # Architecture specific extensions/prefixes *.[568vq] diff --git a/vendor/github.com/go-playground/validator/v10/.golangci.yaml b/vendor/github.com/go-playground/validator/v10/.golangci.yaml index e69d817be1..65efd23828 100644 --- a/vendor/github.com/go-playground/validator/v10/.golangci.yaml +++ b/vendor/github.com/go-playground/validator/v10/.golangci.yaml @@ -14,6 +14,7 @@ linters: - errorlint - exhaustive - exhaustruct + - exhaustruct_v5 - forbidigo - forcetypeassert - funlen diff --git a/vendor/github.com/go-playground/validator/v10/Makefile b/vendor/github.com/go-playground/validator/v10/Makefile index e7caab7f12..bb494a227e 100644 --- a/vendor/github.com/go-playground/validator/v10/Makefile +++ b/vendor/github.com/go-playground/validator/v10/Makefile @@ -3,7 +3,7 @@ GOCMD=go linters-install: @golangci-lint --version >/dev/null 2>&1 || { \ echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.0.2; \ + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.13.1; \ } lint: linters-install diff --git a/vendor/github.com/go-playground/validator/v10/README.md b/vendor/github.com/go-playground/validator/v10/README.md index 8462d21149..8129082d23 100644 --- a/vendor/github.com/go-playground/validator/v10/README.md +++ b/vendor/github.com/go-playground/validator/v10/README.md @@ -85,7 +85,7 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | eqcsfield | Field Equals Another Field (relative)| | eqfield | Field Equals Another Field | | fieldcontains | Check the indicated characters are present in the Field | -| fieldexcludes | Check the indicated characters are not present in the field | +| fieldexcludes | Current field does not contain another field's value | | gtcsfield | Field Greater Than Another Relative Field | | gtecsfield | Field Greater Than or Equal To Another Relative Field | | gtefield | Field Greater Than or Equal To Another Field | @@ -132,6 +132,7 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | origin | Web origin (URL with HTTP(S) scheme and host, but no path/query/fragment) | | url_encoded | URL Encoded | | urn_rfc2141 | Urn RFC 2141 String | +| urn_rfc8141 | Urn RFC 8141 String | ### Strings: diff --git a/vendor/github.com/go-playground/validator/v10/baked_in.go b/vendor/github.com/go-playground/validator/v10/baked_in.go index 679729a5fd..eb1c66c45b 100644 --- a/vendor/github.com/go-playground/validator/v10/baked_in.go +++ b/vendor/github.com/go-playground/validator/v10/baked_in.go @@ -143,6 +143,7 @@ var ( "https_url": isHttpsURL, "uri": isURI, "origin": isOrigin, + "urn_rfc8141": isUrnRFC8141, // RFC 8141 "urn_rfc2141": isUrnRFC2141, // RFC 2141 "file": isFile, "filepath": isFilePath, @@ -1695,6 +1696,26 @@ func isHttpsURL(fl FieldLevel) bool { panic(fmt.Sprintf("Bad field type %s", field.Type())) } +// isUrnRFC8141 is the validation function for validating if the current field's value is a valid URN as per RFC 8141. +func isUrnRFC8141(fl FieldLevel) bool { + field := fl.Field() + + switch field.Kind() { + case reflect.String: + + str := field.String() + if str == "" { + return false + } + + _, match := urn.Parse([]byte(str), urn.WithParsingMode(urn.RFC8141Only)) + + return match + } + + panic(fmt.Sprintf("Bad field type %T", field.Interface())) +} + // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. func isUrnRFC2141(fl FieldLevel) bool { field := fl.Field() @@ -2896,7 +2917,7 @@ func isHostnameRFC1123(fl FieldLevel) bool { func isFQDN(fl FieldLevel) bool { val := fl.Field().String() - if val == "" { + if val == "" || len(strings.TrimSuffix(val, ".")) > 253 { return false } @@ -3024,9 +3045,18 @@ func isHostnamePort(fl FieldLevel) bool { // IsPort validates if the current field's value represents a valid port func isPort(fl FieldLevel) bool { - val := fl.Field().Uint() + field := fl.Field() - return val >= 1 && val <= 65535 + switch field.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + val := field.Int() + return val >= 1 && val <= 65535 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + val := field.Uint() + return val >= 1 && val <= 65535 + default: + panic(fmt.Sprintf("Bad field type %s", field.Type())) + } } // isLowercase is the validation function for validating if the current field's value is a lowercase string. @@ -3510,4 +3540,3 @@ var ( errMethodReturnNoValues = errors.New(`method return o values (void)`) errMethodReturnInvalidType = errors.New(`method should return invalid type`) ) - diff --git a/vendor/github.com/go-playground/validator/v10/doc.go b/vendor/github.com/go-playground/validator/v10/doc.go index 7b1fd078b6..2db8794a73 100644 --- a/vendor/github.com/go-playground/validator/v10/doc.go +++ b/vendor/github.com/go-playground/validator/v10/doc.go @@ -803,13 +803,14 @@ other types. Usage: containsfield=InnerStructField.Field -# Field Excludes Another Field +# Field Excludes Another Field's Value -This does the same as excludes except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. +This validates that the current field's string value does not contain the +string value of the field named by the parameter. It should only be used with +string types. If the referenced field cannot be resolved, validation succeeds. +See the behavior of reflect.Value.String() for behavior on other types. - Usage: excludesfield=InnerStructField.Field + Usage: fieldexcludes=InnerStructField.Field # Unique @@ -1026,6 +1027,13 @@ This will accept any uri the golang request uri accepts Usage: uri +# Urn RFC 8141 String + +This validataes that a string value contains a valid URN +according to the RFC 8141 spec. + + Usage: urn_rfc8141 + # Urn RFC 2141 String This validates that a string value contains a valid URN @@ -1437,7 +1445,7 @@ can be used to validate fields typically passed to sockets and connections. # Port -This validates that the value falls within the valid port number range of 1 to 65,535. +This validates that an integer value (signed or unsigned) falls within the valid port range of 1-65,535. Usage: port diff --git a/vendor/github.com/go-playground/validator/v10/translations/en/en.go b/vendor/github.com/go-playground/validator/v10/translations/en/en.go index 516d54cf8d..e670e2ebfe 100644 --- a/vendor/github.com/go-playground/validator/v10/translations/en/en.go +++ b/vendor/github.com/go-playground/validator/v10/translations/en/en.go @@ -310,7 +310,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return } - if err = ut.Add("max-items", "{0} must contain at maximum {1}", false); err != nil { + if err = ut.Add("max-items", "{0} must contain at most {1}", false); err != nil { return } if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { @@ -548,7 +548,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er { tag: "lte", customRegisFunc: func(ut ut.Translator) (err error) { - if err = ut.Add("lte-string", "{0} must be at maximum {1} in length", false); err != nil { + if err = ut.Add("lte-string", "{0} must be at most {1} in length", false); err != nil { return } @@ -564,7 +564,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return } - if err = ut.Add("lte-items", "{0} must contain at maximum {1}", false); err != nil { + if err = ut.Add("lte-items", "{0} must contain at most {1}", false); err != nil { return } @@ -1187,6 +1187,62 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return t }, }, + { + tag: "startswith", + translation: "{0} must start with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "endswith", + translation: "{0} must end with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "startsnotwith", + translation: "{0} must not start with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "endsnotwith", + translation: "{0} must not end with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, { tag: "excludes", translation: "{0} cannot contain the text '{1}'", diff --git a/vendor/github.com/leodido/go-urn/machine.go b/vendor/github.com/leodido/go-urn/machine.go index aec1ba69cb..82d058673c 100644 --- a/vendor/github.com/leodido/go-urn/machine.go +++ b/vendor/github.com/leodido/go-urn/machine.go @@ -24,6 +24,7 @@ var ( err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]" err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" + errInvalidSyntax = "invalid URN syntax [col %d]" ) var _toStateActions []byte = []byte{ 0, 0, 0, 0, 0, 0, 0, 0, @@ -4358,7 +4359,7 @@ func (m *machine) Parse(input []byte) (*URN, error) { if m.parsingMode != RFC8141Only { // Throw an error when: - // - we are entering here matching the the prefix in the namespace identifier part + // - we are entering here matching the prefix in the namespace identifier part // - looking ahead (3 chars) we find a colon if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" { m.err = fmt.Errorf(errNoUrnWithinID, pos) @@ -5026,6 +5027,9 @@ func (m *machine) Parse(input []byte) (*URN, error) { } if m.cs < firstFinal || m.cs == enFail { + if m.err == nil { + m.err = fmt.Errorf(errInvalidSyntax, m.p) + } return nil, m.err } diff --git a/vendor/github.com/leodido/go-urn/machine.go.rl b/vendor/github.com/leodido/go-urn/machine.go.rl index 0a17421998..481e12fd5c 100644 --- a/vendor/github.com/leodido/go-urn/machine.go.rl +++ b/vendor/github.com/leodido/go-urn/machine.go.rl @@ -24,6 +24,7 @@ var ( err8141QComponentStart = "expecting only one q-component (starting with the ?= sequence) [col %d]" err8141MalformedRComp = "expecting a non-empty r-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" err8141MalformedQComp = "expecting a non-empty q-component containing alnum, hex, or others ([~&()+,-.:=@;$_!*'] or [/?] but not at its beginning) [col %d]" + errInvalidSyntax = "invalid URN syntax [col %d]" ) %%{ @@ -48,7 +49,7 @@ action set_pre { action throw_pre_urn_err { if m.parsingMode != RFC8141Only { // Throw an error when: - // - we are entering here matching the the prefix in the namespace identifier part + // - we are entering here matching the prefix in the namespace identifier part // - looking ahead (3 chars) we find a colon if pos := m.p + 3; pos < m.pe && m.data[pos] == 58 && output.prefix != "" { m.err = fmt.Errorf(errNoUrnWithinID, pos) @@ -366,6 +367,9 @@ func (m *machine) Parse(input []byte) (*URN, error) { %% write exec; if m.cs < first_final || m.cs == en_fail { + if m.err == nil { + m.err = fmt.Errorf(errInvalidSyntax, m.p) + } return nil, m.err } @@ -383,4 +387,4 @@ func (m *machine) WithParsingMode(x ParsingMode) { m.startParsingAt = en_scim_only } m.parsingModeSet = true -} \ No newline at end of file +} diff --git a/vendor/github.com/leodido/go-urn/urn.go b/vendor/github.com/leodido/go-urn/urn.go index 894d6258dc..3c2110dc29 100644 --- a/vendor/github.com/leodido/go-urn/urn.go +++ b/vendor/github.com/leodido/go-urn/urn.go @@ -8,7 +8,7 @@ import ( const errInvalidURN = "invalid URN: %s" -// URN represents an Uniform Resource Name. +// URN represents a Uniform Resource Name. // // The general form represented is: // @@ -32,7 +32,7 @@ type URN struct { // Normalize turns the receiving URN into its norm version. // -// Which means: lowercase prefix, lowercase namespace identifier, and immutate namespace specific string chars (except tokens which are lowercased). +// Which means: lowercase prefix, lowercase namespace identifier, and leave namespace-specific string chars unchanged (except tokens which are lowercased). func (u *URN) Normalize() *URN { return &URN{ prefix: "urn", @@ -82,10 +82,10 @@ func (u *URN) String() string { return res } -// Parse is responsible to create an URN instance from a byte array matching the correct URN syntax (RFC 2141). +// Parse is responsible for creating a URN instance from a byte array matching the correct URN syntax (RFC 2141). func Parse(u []byte, options ...Option) (*URN, bool) { urn, err := NewMachine(options...).Parse(u) - if err != nil { + if err != nil || urn == nil { return nil, false } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go index bd35436f79..8f8b61fff7 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/grpc/interceptors/eventsmiddleware/conversion.go @@ -69,7 +69,7 @@ func ShareRemoved(r *collaboration.RemoveShareResponse, req *collaboration.Remov rid *provider.ResourceId ) _ = utils.ReadJSONFromOpaque(r.Opaque, "granteeuserid", &userid) - _ = utils.ReadJSONFromOpaque(r.Opaque, "granteegroupid", &userid) + _ = utils.ReadJSONFromOpaque(r.Opaque, "granteegroupid", &groupid) _ = utils.ReadJSONFromOpaque(r.Opaque, "resourceid", &rid) return events.ShareRemoved{ Executant: executant.GetId(), diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/basic/basic.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/basic/basic.go index 7b7bec0727..45decb911a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/basic/basic.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/basic/basic.go @@ -52,5 +52,5 @@ func (s *strategy) AddWWWAuthenticate(w http.ResponseWriter, r *http.Request, re // fall back to hostname if not configured realm = r.Host } - w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm)) + w.Header().Add("WWW-Authenticate", auth.Challenge("Basic", realm)) } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go index 62168019f0..3ed45596cf 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go @@ -63,5 +63,5 @@ func (s *strategy) AddWWWAuthenticate(w http.ResponseWriter, r *http.Request, re // fall back to hostname if not configured realm = r.Host } - w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Bearer realm="%s"`, realm)) + w.Header().Add("WWW-Authenticate", auth.Challenge("Bearer", realm)) } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/dav.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/dav.go index 30dd16ab9c..2b1c0bc91b 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/dav.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/dav.go @@ -20,7 +20,6 @@ package ocdav import ( "context" - "fmt" "net/http" "path" "path/filepath" @@ -35,6 +34,7 @@ import ( "github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/errors" "github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/net" "github.com/opencloud-eu/reva/v2/pkg/appctx" + "github.com/opencloud-eu/reva/v2/pkg/auth" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" "github.com/opencloud-eu/reva/v2/pkg/rhttp/router" @@ -438,7 +438,7 @@ func handleBasicAuth(ctx context.Context, selector pool.Selectable[gatewayv1beta } func authChallenge(scheme, realm string) string { - return fmt.Sprintf("%s realm=\"%s\", charset=\"UTF-8\"", scheme, realm) + return auth.Challenge(scheme, realm, `charset="UTF-8"`) } func handleSignatureAuth(ctx context.Context, selector pool.Selectable[gatewayv1beta1.GatewayAPIClient], token, sig, expiration string) (*gatewayv1beta1.AuthenticateResponse, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/propfind/propfind.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/propfind/propfind.go index da869a905b..f707a2b1ff 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/propfind/propfind.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/owncloud/ocdav/propfind/propfind.go @@ -1538,6 +1538,8 @@ func mdToPropResponse(ctx context.Context, pf *XML, md *provider.ResourceInfo, p types.WriteString("" + strconv.Itoa(int(conversions.ShareTypeUser)) + "") case "2": // provider.GranteeType_GRANTEE_TYPE_GROUP types.WriteString("" + strconv.Itoa(int(conversions.ShareTypeGroup)) + "") + case "4": // conversions.ShareTypeGuest, guest shares are stored as user grants + types.WriteString("" + strconv.Itoa(int(conversions.ShareTypeGuest)) + "") default: sublog.Debug().Interface("shareType", shareType).Msg("unknown share type, ignoring") } diff --git a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/sciencemesh/wayf.go b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/sciencemesh/wayf.go index 11d08611e2..783ade5f02 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/sciencemesh/wayf.go +++ b/vendor/github.com/opencloud-eu/reva/v2/internal/http/services/sciencemesh/wayf.go @@ -21,9 +21,11 @@ package sciencemesh import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/url" + "path" "strings" "time" @@ -47,20 +49,56 @@ type DiscoverResponse struct { InviteAcceptDialog string `json:"inviteAcceptDialog"` } -// makeAbsoluteURL takes a base URL and a path/URL and returns an absolute URL. -// If dialogURL is already absolute (has scheme and host), it returns it as-is. -// Otherwise, it joins the dialogURL with the baseURL to create an absolute URL. -func makeAbsoluteURL(baseURL, dialogURL string) (string, error) { - if dialogURL == "" { - return "", nil +var ( + errInvalidProviderURL = errors.New("invalid provider URL") + errInvalidInviteDialog = errors.New("invalid invite accept dialog") +) + +// resolveInviteAcceptDialog builds the invite page on the provider origin. +// The discovery value is a path. An absolute URL is accepted only when its +// scheme and host, including port, match the provider; the result is rebuilt +// from those fields and the path, never returned as received. +func resolveInviteAcceptDialog(providerBase, dialog string) (string, error) { + base, err := url.Parse(providerBase) + if err != nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" || base.User != nil { + return "", errInvalidProviderURL } - parsed, err := url.Parse(dialogURL) - if err == nil && parsed.Scheme != "" && parsed.Host != "" { - return dialogURL, nil + dialog = strings.TrimSpace(dialog) + if dialog == "" || strings.ContainsAny(dialog, "\\#") || containsControl(dialog) { + return "", errInvalidInviteDialog + } + ref, err := url.Parse(dialog) + if err != nil || ref.Opaque != "" || ref.User != nil { + return "", errInvalidInviteDialog + } + if (ref.Scheme != "" || ref.Host != "") && + (ref.Scheme != base.Scheme || !strings.EqualFold(ref.Host, base.Host)) { + return "", errInvalidInviteDialog } - return url.JoinPath(baseURL, dialogURL) + p := ref.Path + if ref.Scheme != "" && p == "" { + p = "/" + } + if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || + strings.ContainsAny(p, "\\?#") || containsControl(p) { + return "", errInvalidInviteDialog + } + p = path.Clean(p) + if !strings.HasPrefix(p, "/") { + return "", errInvalidInviteDialog + } + return (&url.URL{Scheme: base.Scheme, Host: base.Host, Path: p}).String(), nil +} + +func containsControl(s string) bool { + for _, r := range s { + if r < 0x20 || r == 0x7f { + return true + } + } + return false } func (h *wayfHandler) init(c *config) error { @@ -130,20 +168,20 @@ func (h *wayfHandler) init(c *config) error { inviteDialog := disco.InviteAcceptDialog if inviteDialog != "" { - absoluteURL, err := makeAbsoluteURL(srv.URL, inviteDialog) + resolved, err := resolveInviteAcceptDialog(srv.URL, inviteDialog) if err != nil { log.Debug().Err(err). Str("federation", directoryService.Federation). Str("server", srv.DisplayName). Str("url", srv.URL). Str("inviteDialog", disco.InviteAcceptDialog). - Msg("Failed to construct absolute URL, skipping server") + Msg("Invalid invite accept dialog, skipping server") continue } - if absoluteURL != inviteDialog { - log.Debug().Str("original", inviteDialog).Str("absolute", absoluteURL).Msg("Converted to absolute URL") + if resolved != inviteDialog { + log.Debug().Str("original", inviteDialog).Str("resolved", resolved).Msg("Resolved invite accept dialog") } - inviteDialog = absoluteURL + inviteDialog = resolved } validServers = append(validServers, ocmd.DirectoryServiceServer{ @@ -227,19 +265,15 @@ func (h *wayfHandler) DiscoverProvider(w http.ResponseWriter, r *http.Request) { return } - inviteDialog := disco.InviteAcceptDialog - - if inviteDialog == "" { - log.Info().Str("domain", domain).Msg("Provider does not provide invite accept dialog") - reqres.WriteError(w, r, reqres.APIErrorNotFound, - fmt.Sprintf("Provider at '%s' does not provide an invite accept dialog", req.Domain), nil) - return - } - - inviteDialog, err = makeAbsoluteURL(domain, inviteDialog) + inviteDialog, err := resolveInviteAcceptDialog(domain, disco.InviteAcceptDialog) if err != nil { - log.Info().Err(err).Str("domain", domain).Str("inviteDialog", disco.InviteAcceptDialog).Msg("Failed to construct invite accept dialog URL") - reqres.WriteError(w, r, reqres.APIErrorServerError, "Failed to construct invite accept dialog URL", err) + log.Info().Err(err).Str("domain", domain).Str("inviteDialog", disco.InviteAcceptDialog).Msg("Provider does not provide a usable invite accept dialog") + if errors.Is(err, errInvalidProviderURL) { + reqres.WriteError(w, r, reqres.APIErrorInvalidParameter, "Invalid domain format", err) + return + } + reqres.WriteError(w, r, reqres.APIErrorNotFound, + fmt.Sprintf("Provider at '%s' does not provide an invite accept dialog", req.Domain), err) return } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/auth/challenge.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/auth/challenge.go new file mode 100644 index 0000000000..b4091811f0 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/auth/challenge.go @@ -0,0 +1,14 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package auth + +import "strings" + +var quotedStringEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`) + +// Challenge builds a WWW-Authenticate challenge for the given scheme with the +// realm escaped as a quoted-string. Additional params are appended without escaping. +func Challenge(scheme, realm string, params ...string) string { + return strings.Join(append([]string{scheme + ` realm="` + quotedStringEscaper.Replace(realm) + `"`}, params...), ", ") +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/conversions/main.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/conversions/main.go index 699dd89961..bf013d438e 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/conversions/main.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/conversions/main.go @@ -61,6 +61,9 @@ const ( // ShareTypeSpaceMembershipGroup represents an action regarding group type space members ShareTypeSpaceMembershipGroup ShareType = 8 + // ShareTypeGuest represents a guest share + ShareTypeGuest ShareType = 4 + // ShareWithUserTypeUser represents a normal user ShareWithUserTypeUser ShareWithUserType = 0 diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/mime/mime.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/mime/mime.go index f88ba5cc18..42324a48f1 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/mime/mime.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/mime/mime.go @@ -33,6 +33,7 @@ var mimeTypes = map[string]string{ "3g2": "video/3gpp2", "3gp": "video/3gpp", "3gpp": "video/3gpp", + "3mf": "model/3mf", "7z": "application/x-7z-compressed", "aab": "application/x-authorware-bin", "aac": "audio/x-aac", @@ -49,7 +50,7 @@ var mimeTypes = map[string]string{ "afm": "application/x-font-type1", "afp": "application/vnd.ibm.modcap", "ahead": "application/vnd.ahead.space", - "ai": "application/postscript", + "ai": "application/illustrator", "aif": "audio/x-aiff", "aifc": "audio/x-aiff", "aiff": "audio/x-aiff", @@ -82,6 +83,7 @@ var mimeTypes = map[string]string{ "azs": "application/vnd.airzip.filesecure.azs", "azv": "image/vnd.airzip.accelerator.azv", "azw": "application/vnd.amazon.ebook", + "azw3": "application/vnd.amazon.mobi8-ebook", "bat": "application/x-msdownload", "bcpio": "application/x-bcpio", "bdf": "application/x-font-bdf", @@ -91,6 +93,7 @@ var mimeTypes = map[string]string{ "bh2": "application/vnd.fujitsu.oasysprs", "bin": "application/octet-stream", "blb": "application/x-blorb", + "blend": "application/x-blender", "blorb": "application/x-blorb", "bmi": "application/vnd.bmi", "bmp": "image/x-ms-bmp", @@ -115,11 +118,11 @@ var mimeTypes = map[string]string{ "cap": "application/vnd.tcpdump.pcap", "car": "application/vnd.curl.car", "cat": "application/vnd.ms-pki.seccat", - "cb7": "application/x-cbr", + "cb7": "application/x-cb7", "cba": "application/x-cbr", - "cbr": "application/x-cbr", - "cbt": "application/x-cbr", - "cbz": "application/x-cbr", + "cbr": "application/vnd.comicbook-rar", + "cbt": "application/x-cbt", + "cbz": "application/vnd.comicbook+zip", "cc": "text/x-c", "cco": "application/x-cocoa", "cct": "application/x-director", @@ -165,6 +168,7 @@ var mimeTypes = map[string]string{ "cpp": "text/x-c", "cpt": "application/mac-compactpro", "cr2": "image/x-canon-cr2", + "cr3": "image/x-canon-cr3", "crd": "application/x-mscardfile", "crl": "application/pkix-crl", "crt": "application/x-x509-ca-cert", @@ -276,6 +280,7 @@ var mimeTypes = map[string]string{ "f4v": "video/x-f4v", "f77": "text/x-fortran", "f90": "text/x-fortran", + "fb2": "application/x-fictionbook+xml", "fbs": "image/vnd.fastbidsheet", "fcdt": "application/vnd.adobe.formscentral.fcdt", "fcs": "application/vnd.isac.fcs", @@ -407,6 +412,7 @@ var mimeTypes = map[string]string{ "iota": "application/vnd.astraea-software.iota", "ipfix": "application/ipfix", "ipk": "application/vnd.shana.informed.package", + "ipynb": "application/x-ipynb+json", "irm": "application/vnd.ibm.rights-management", "irp": "application/vnd.irepository.package+xml", "iso": "application/x-iso9660-image", @@ -456,6 +462,7 @@ var mimeTypes = map[string]string{ "kpr": "application/vnd.kde.kpresenter", "kpt": "application/vnd.kde.kpresenter", "kpxx": "application/vnd.ds-keypoint", + "kra": "application/x-krita", "ksp": "application/vnd.kde.kspread", "ktr": "application/vnd.kahootz", "ktx": "image/ktx", @@ -495,6 +502,7 @@ var mimeTypes = map[string]string{ "m3u": "audio/x-mpegurl", "m3u8": "application/vnd.apple.mpegurl", "m4a": "audio/x-m4a", + "m4b": "audio/x-m4b", "m4p": "application/mp4", "m4u": "video/vnd.mpegurl", "m4v": "video/x-m4v", @@ -648,6 +656,7 @@ var mimeTypes = map[string]string{ "opf": "application/oebps-package+xml", "opml": "text/x-opml", "oprc": "application/vnd.palm", + "ora": "image/openraster", "orf": "image/x-olympus-orf", "org": "text/x-org", "osf": "application/vnd.yamaha.openscoreformat", diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go index 80ca36c2c1..79441f69c3 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics/metrics.go @@ -1,4 +1,4 @@ -// Package metrics provides prometheus metrics for the data managers.. +// Package metrics provides prometheus metrics for the data managers. package metrics import ( @@ -25,36 +25,38 @@ var ( // UploadSessionsInitiated is the number of upload sessions that have been initiated UploadSessionsInitiated = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_initiated", - Help: "Number of uploads sessions that were initiated", + Help: "Number of upload sessions that were initiated", }) - // UploadSessionsBytesReceived is the number of upload sessions that have received all bytes + // UploadSessionsBytesReceived counts upload sessions whose data has been fully received and is + // safely stored, before postprocessing decides their outcome; it counts sessions, not bytes, + // despite its name (kept for compatibility, see https://github.com/opencloud-eu/reva/issues/930) UploadSessionsBytesReceived = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_bytes_received", - Help: "Number of uploads sessions that have received all bytes", + Help: "Number of upload sessions whose data has been fully received, before postprocessing (counts sessions, not bytes)", }) - // UploadSessionsFinalized is the number of upload sessions that have received all bytes + // UploadSessionsFinalized is the number of upload sessions that have successfully completed UploadSessionsFinalized = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_finalized", - Help: "Number of uploads sessions that have successfully completed", + Help: "Number of upload sessions that have successfully completed", }) // UploadSessionsAborted is the number of upload sessions that have been aborted UploadSessionsAborted = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_aborted", - Help: "Number of uploads sessions that have aborted by postprocessing", + Help: "Number of upload sessions that have been aborted by postprocessing", }) // UploadSessionsDeleted is the number of upload sessions that have been deleted UploadSessionsDeleted = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_deleted", - Help: "Number of uploads sessions that have been deleted by postprocessing", + Help: "Number of upload sessions that have been deleted by postprocessing", }) // UploadSessionsRestarted is the number of upload sessions that have been restarted UploadSessionsRestarted = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_restarted", - Help: "Number of uploads sessions that have been restarted by postprocessing", + Help: "Number of upload sessions that have been restarted by postprocessing", }) // UploadSessionsScanned is the number of upload sessions that have been scanned by antivirus UploadSessionsScanned = promauto.NewCounter(prometheus.CounterOpts{ Name: "reva_upload_sessions_scanned", - Help: "Number of uploads sessions that have been scanned by antivirus", + Help: "Number of upload sessions that have been scanned by antivirus", }) ) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/providercache/providercache.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/providercache/providercache.go index 7ed0f40bf3..a8149d983a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/providercache/providercache.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/providercache/providercache.go @@ -33,7 +33,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/mtimesyncedcache" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/metadata" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go index b8e536b082..be39b7c990 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/receivedsharecache/receivedsharecache.go @@ -32,7 +32,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/mtimesyncedcache" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/metadata" "github.com/opencloud-eu/reva/v2/pkg/utils" "go.opentelemetry.io/otel/attribute" diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/sharecache/sharecache.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/sharecache/sharecache.go index c5a812dc16..ae85b17d22 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/sharecache/sharecache.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/sharecache/sharecache.go @@ -35,7 +35,7 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/appctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/share/manager/jsoncs3/shareid" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache" + "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/mtimesyncedcache" "github.com/opencloud-eu/reva/v2/pkg/storage/utils/metadata" "github.com/opencloud-eu/reva/v2/pkg/utils" ) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/loader/loader.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/loader/loader.go index c3e05a4f4c..e73d0a4ac3 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/loader/loader.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/loader/loader.go @@ -31,9 +31,7 @@ import ( _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/local" _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/localhome" _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud" - _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis" _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql" _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix" - _ "github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng" // Add your own here ) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore/blobstore.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore/blobstore.go deleted file mode 100644 index 2d21a94cb9..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore/blobstore.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package blobstore - -import ( - "bufio" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" -) - -// ErrBlobIDEmpty is returned when the BlobID is empty -var ErrBlobIDEmpty = fmt.Errorf("blobstore: BlobID is empty") - -// Blobstore provides an interface to an filesystem based blobstore -type Blobstore struct { - root string -} - -// New returns a new Blobstore -func New(root string) (*Blobstore, error) { - err := os.MkdirAll(root, 0700) - if err != nil { - return nil, err - } - - return &Blobstore{ - root: root, - }, nil -} - -// Upload stores some data in the blobstore under the given key -func (bs *Blobstore) Upload(node *node.Node, source string) (err error) { - if node.BlobID == "" { - return ErrBlobIDEmpty - } - - dest := bs.Path(node) - - // ensure parent path exists - if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: oCIS blobstore: error creating parent folders for blob") - } - - if err := os.Rename(source, dest); err == nil { - return nil - } - - // Rename failed, file needs to be copied. - file, err := os.Open(source) - if err != nil { - return errors.Wrap(err, "Decomposedfs: oCIS blobstore: Can not open source file to upload") - } - defer file.Close() - - f, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0700) - if err != nil { - return errors.Wrapf(err, "could not open blob '%s' for writing", dest) - } - defer func() { - if cerr := f.Close(); cerr != nil && err == nil { - err = errors.Wrapf(cerr, "could not close blob '%s'", dest) - } - }() - - w := bufio.NewWriter(f) - if _, err = w.ReadFrom(file); err != nil { - return errors.Wrapf(err, "could not write blob '%s'", dest) - } - - if err = w.Flush(); err != nil { - return errors.Wrapf(err, "could not flush blob '%s'", dest) - } - - // Ensure data is synced to disk before returning - if err = f.Sync(); err != nil { - return errors.Wrapf(err, "could not sync blob '%s' to disk", dest) - } - - return nil -} - -// UploadFromReader stores data from a reader in the blobstore under the given key. -// It buffers to a temp file on the same filesystem as the destination so that the -// final placement is an atomic os.Rename. -func (bs *Blobstore) UploadFromReader(node *node.Node, r io.Reader, size int64) error { - if node.BlobID == "" { - return ErrBlobIDEmpty - } - - dest := bs.Path(node) - - if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: oCIS blobstore: error creating parent folders for blob") - } - - tmp, err := os.CreateTemp(filepath.Dir(dest), "reva-blobstore-upload-*") - if err != nil { - return errors.Wrap(err, "Decomposedfs: oCIS blobstore: error creating temp file for upload") - } - tmpName := tmp.Name() - defer func() { - tmp.Close() - os.Remove(tmpName) - }() - - w := bufio.NewWriter(tmp) - if _, err = io.Copy(w, r); err != nil { - return errors.Wrapf(err, "could not write blob to temp file '%s'", tmpName) - } - if err = w.Flush(); err != nil { - return errors.Wrapf(err, "could not flush blob temp file '%s'", tmpName) - } - if err = tmp.Sync(); err != nil { - return errors.Wrapf(err, "could not sync blob temp file '%s'", tmpName) - } - tmp.Close() - - if err = os.Rename(tmpName, dest); err != nil { - return errors.Wrapf(err, "could not rename blob temp file to '%s'", dest) - } - return nil -} - -// Download retrieves a blob from the blobstore for reading -func (bs *Blobstore) Download(node *node.Node) (io.ReadCloser, error) { - if node.BlobID == "" { - return nil, ErrBlobIDEmpty - } - - dest := bs.Path(node) - file, err := os.Open(dest) - if err != nil { - return nil, errors.Wrapf(err, "could not read blob '%s'", dest) - } - return file, nil -} - -// Delete deletes a blob from the blobstore -func (bs *Blobstore) Delete(node *node.Node) error { - if node.BlobID == "" { - return ErrBlobIDEmpty - } - dest := bs.Path(node) - if err := utils.RemoveItem(dest); err != nil { - return errors.Wrapf(err, "could not delete blob '%s'", dest) - } - return nil -} - -// List lists all blobs in the Blobstore -func (bs *Blobstore) List() ([]*node.Node, error) { - dirs, err := filepath.Glob(filepath.Join(bs.root, "spaces", "*", "*", "blobs", "*", "*", "*", "*", "*")) - if err != nil { - return nil, err - } - blobids := make([]*node.Node, 0, len(dirs)) - for _, d := range dirs { - _, s, _ := strings.Cut(d, "spaces") - spaceraw, blobraw, _ := strings.Cut(s, "blobs") - blobids = append(blobids, &node.Node{ - SpaceID: strings.ReplaceAll(spaceraw, "/", ""), - BlobID: strings.ReplaceAll(blobraw, "/", ""), - }) - } - return blobids, nil -} - -func (bs *Blobstore) Path(node *node.Node) string { - return filepath.Join( - bs.root, - filepath.Clean(filepath.Join( - "/", "spaces", lookup.Pathify(node.SpaceID, 1, 2), "blobs", lookup.Pathify(node.BlobID, 4, 2)), - ), - ) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/ocis.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/ocis.go deleted file mode 100644 index 3b6687c1a7..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/ocis.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package ocis - -import ( - "path" - - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore" - "github.com/opencloud-eu/reva/v2/pkg/storage/fs/registry" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/rs/zerolog" -) - -func init() { - registry.Register("ocis", New) -} - -// New returns an implementation to of the storage.FS interface that talk to -// a local filesystem. -func New(m map[string]interface{}, stream events.Stream, log *zerolog.Logger) (storage.FS, error) { - o, err := options.New(m) - if err != nil { - return nil, err - } - - bs, err := blobstore.New(path.Join(o.Root)) - if err != nil { - return nil, err - } - - return decomposedfs.NewDefault(m, bs, stream, log) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/trashbin/trashbin.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/trashbin/trashbin.go index 46487dfea2..87e2fa7ad3 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/trashbin/trashbin.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/trashbin/trashbin.go @@ -20,6 +20,7 @@ package trashbin import ( "context" + "errors" "fmt" "io" "io/fs" @@ -332,6 +333,9 @@ func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, spaceID string, key, } else { originalPath, _, err := tb.readInfoFile(trashRoot, key) if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil, errtypes.NotFound(key) + } return nil, err } restorePath = filepath.Join(tb.lu.InternalPath(spaceID, spaceID), originalPath, relativePath) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore/blobstore.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore/blobstore.go deleted file mode 100644 index 628105a183..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore/blobstore.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package blobstore - -import ( - "context" - "fmt" - "io" - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/minio/minio-go/v7" - "github.com/minio/minio-go/v7/pkg/credentials" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/pkg/errors" -) - -// Blobstore provides an interface to an s3 compatible blobstore -type Blobstore struct { - client *minio.Client - - defaultPutOptions Options - - bucket string -} - -type Options struct { - DisableContentSha256 bool - DisableMultipart bool - SendContentMd5 bool - ConcurrentStreamParts bool - NumThreads uint - PartSize uint64 -} - -// New returns a new Blobstore -func New(endpoint, region, bucket, accessKey, secretKey string, defaultPutOptions Options) (*Blobstore, error) { - u, err := url.Parse(endpoint) - if err != nil { - return nil, errors.Wrap(err, "failed to parse s3 endpoint") - } - - useSSL := u.Scheme != "http" - client, err := minio.New(u.Host, &minio.Options{ - Region: region, - Creds: credentials.NewStaticV4(accessKey, secretKey, ""), - Secure: useSSL, - }) - if err != nil { - return nil, errors.Wrap(err, "failed to setup s3 client") - } - - return &Blobstore{ - client: client, - bucket: bucket, - defaultPutOptions: defaultPutOptions, - }, nil -} - -// Upload stores some data in the blobstore under the given key -// TODO(OCISDEV-901): remove once FinishUploadDecomposed is replaced by the upload coordinator (OCISDEV-900). -func (bs *Blobstore) Upload(node *node.Node, source string) error { - reader, err := os.Open(source) - if err != nil { - return errors.Wrap(err, "can not open source file to upload") - } - defer reader.Close() - - _, err = bs.client.PutObject(context.Background(), bs.bucket, bs.Path(node), reader, node.Blobsize, minio.PutObjectOptions{ - ContentType: "application/octet-stream", - SendContentMd5: bs.defaultPutOptions.SendContentMd5, - ConcurrentStreamParts: bs.defaultPutOptions.ConcurrentStreamParts, - NumThreads: bs.defaultPutOptions.NumThreads, - PartSize: bs.defaultPutOptions.PartSize, - DisableMultipart: bs.defaultPutOptions.DisableMultipart, - DisableContentSha256: bs.defaultPutOptions.DisableContentSha256, - }) - - if err != nil { - return errors.Wrapf(err, "could not store object '%s' into bucket '%s'", bs.Path(node), bs.bucket) - } - return nil -} - -// UploadFromReader stores data from a reader directly into S3 without local buffering. -func (bs *Blobstore) UploadFromReader(node *node.Node, r io.Reader, size int64) error { - _, err := bs.client.PutObject(context.Background(), bs.bucket, bs.Path(node), r, size, minio.PutObjectOptions{ - ContentType: "application/octet-stream", - SendContentMd5: bs.defaultPutOptions.SendContentMd5, - ConcurrentStreamParts: bs.defaultPutOptions.ConcurrentStreamParts, - NumThreads: bs.defaultPutOptions.NumThreads, - PartSize: bs.defaultPutOptions.PartSize, - DisableMultipart: bs.defaultPutOptions.DisableMultipart, - DisableContentSha256: bs.defaultPutOptions.DisableContentSha256, - }) - if err != nil { - return errors.Wrapf(err, "could not store object '%s' into bucket '%s'", bs.Path(node), bs.bucket) - } - return nil -} - -// Download retrieves a blob from the blobstore for reading -func (bs *Blobstore) Download(node *node.Node) (io.ReadCloser, error) { - reader, err := bs.client.GetObject(context.Background(), bs.bucket, bs.Path(node), minio.GetObjectOptions{}) - if err != nil { - return nil, errors.Wrapf(err, "could not download object '%s' from bucket '%s'", bs.Path(node), bs.bucket) - } - - stat, err := reader.Stat() - if err != nil { - return nil, errors.Wrapf(err, "blob path: %s", bs.Path(node)) - } - - if node.Blobsize != stat.Size { - return nil, fmt.Errorf("blob has unexpected size. %d bytes expected, got %d bytes", node.Blobsize, stat.Size) - } - - return reader, nil -} - -// Delete deletes a blob from the blobstore -func (bs *Blobstore) Delete(node *node.Node) error { - err := bs.client.RemoveObject(context.Background(), bs.bucket, bs.Path(node), minio.RemoveObjectOptions{}) - if err != nil { - return errors.Wrapf(err, "could not delete object '%s' from bucket '%s'", bs.Path(node), bs.bucket) - } - return nil -} - -// List lists all blobs in the Blobstore -func (bs *Blobstore) List() ([]*node.Node, error) { - ch := bs.client.ListObjects(context.Background(), bs.bucket, minio.ListObjectsOptions{Recursive: true}) - - var err error - ids := make([]*node.Node, 0) - for oi := range ch { - if oi.Err != nil { - err = oi.Err - continue - } - spaceid, blobid, _ := strings.Cut(oi.Key, "/") - ids = append(ids, &node.Node{ - SpaceID: strings.ReplaceAll(spaceid, "/", ""), - BlobID: strings.ReplaceAll(blobid, "/", ""), - }) - } - return ids, err -} - -func (bs *Blobstore) Path(node *node.Node) string { - // https://aws.amazon.com/de/premiumsupport/knowledge-center/s3-prefix-nested-folders-difference/ - // Prefixes are used to partion a bucket. A prefix is everything except the filename. - // For a file `BucketName/foo/bar/lorem.ipsum`, `BucketName/foo/bar/` is the prefix. - // There are request limits per prefix, therefore you should have many prefixes. - // There are no limits to prefixes per bucket, so in general it's better to have more then less. - // - // Since the spaceID is always the same for a space, we don't need to pathify that, because it would - // not yield any performance gains - return filepath.Clean(filepath.Join(node.SpaceID, lookup.Pathify(node.BlobID, 4, 2))) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/option.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/option.go deleted file mode 100644 index 3f0f3201fd..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/option.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package s3ng - -import ( - "github.com/go-viper/mapstructure/v2" - "github.com/pkg/errors" -) - -// Option defines a single option function. -type Option func(o *Options) - -// Options defines the available options for this package. -type Options struct { - - // Endpoint of the s3 blobstore - S3Endpoint string `mapstructure:"s3.endpoint"` - - // Region of the s3 blobstore - S3Region string `mapstructure:"s3.region"` - - // Bucket of the s3 blobstore - S3Bucket string `mapstructure:"s3.bucket"` - - // Access key for the s3 blobstore - S3AccessKey string `mapstructure:"s3.access_key"` - - // Secret key for the s3 blobstore - S3SecretKey string `mapstructure:"s3.secret_key"` - - // disable sending content sha256 - DisableContentSha256 bool `mapstructure:"s3.disable_content_sha254"` - - // disable multipart uploads - DisableMultipart bool `mapstructure:"s3.disable_multipart"` - - // enable sending content md5, defaults to true if unset - SendContentMd5 bool `mapstructure:"s3.send_content_md5"` - - // use concurrent stream parts - ConcurrentStreamParts bool `mapstructure:"s3.concurrent_stream_parts"` - - // number of concurrent uploads - NumThreads uint `mapstructure:"s3.num_threads"` - - // part size for concurrent uploads - PartSize uint64 `mapstructure:"s3.part_size"` -} - -// S3ConfigComplete return true if all required s3 fields are set -func (o *Options) S3ConfigComplete() bool { - return o.S3Endpoint != "" && - o.S3Region != "" && - o.S3Bucket != "" && - o.S3AccessKey != "" && - o.S3SecretKey != "" -} - -func parseConfig(m map[string]interface{}) (*Options, error) { - o := &Options{} - if err := mapstructure.Decode(m, o); err != nil { - err = errors.Wrap(err, "error decoding conf") - return nil, err - } - - // if unset we set these defaults - if m["s3.send_content_md5"] == nil { - o.SendContentMd5 = true - } - if m["s3.concurrent_stream_parts"] == nil { - o.ConcurrentStreamParts = true - } - if m["s3.num_threads"] == nil { - o.NumThreads = 4 - } - return o, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/s3ng.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/s3ng.go deleted file mode 100644 index 903e224bd0..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/s3ng.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package s3ng - -import ( - "fmt" - - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/fs/registry" - "github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs" - "github.com/rs/zerolog" -) - -func init() { - registry.Register("s3ng", New) -} - -// New returns an implementation to of the storage.FS interface that talk to -// a local filesystem. -func New(m map[string]interface{}, stream events.Stream, log *zerolog.Logger) (storage.FS, error) { - o, err := parseConfig(m) - if err != nil { - return nil, err - } - - if !o.S3ConfigComplete() { - return nil, fmt.Errorf("S3 configuration incomplete") - } - - defaultPutOptions := blobstore.Options{ - DisableContentSha256: o.DisableContentSha256, - DisableMultipart: o.DisableMultipart, - SendContentMd5: o.SendContentMd5, - ConcurrentStreamParts: o.ConcurrentStreamParts, - NumThreads: o.NumThreads, - PartSize: o.PartSize, - } - - bs, err := blobstore.New(o.S3Endpoint, o.S3Region, o.S3Bucket, o.S3AccessKey, o.S3SecretKey, defaultPutOptions) - if err != nil { - return nil, err - } - - return decomposedfs.NewDefault(m, bs, stream, log) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go index 22e4d65c45..557046958a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/decomposedfs.go @@ -41,6 +41,7 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" "golang.org/x/sync/errgroup" + "google.golang.org/protobuf/proto" "github.com/opencloud-eu/reva/v2/pkg/appctx" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" @@ -1113,7 +1114,8 @@ func (fs *Decomposedfs) ListFolder(ctx context.Context, ref *provider.Reference, for i := 0; i < numWorkers; i++ { g.Go(func() error { for child := range work { - np := rp + // copy the parent's permissions: the workers must not share them + np := proto.Clone(rp).(*provider.ResourcePermissions) // add this childs permissions pset, _ := child.PermissionSet(ctx) node.AddPermissions(np, pset) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go index 040740d6f3..80d6e9c588 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/hybrid_backend.go @@ -14,7 +14,6 @@ import ( "github.com/google/renameio/v2" "github.com/pkg/errors" "github.com/pkg/xattr" - "github.com/rogpeppe/go-internal/lockedfile" "github.com/vmihailenco/msgpack/v5" "github.com/opencloud-eu/reva/v2/pkg/storage/cache" @@ -30,6 +29,7 @@ type HybridBackend struct { offloadLimit int metaCache cache.FileMetadataCache metadataPathFunc MetadataPathFunc + metrics *backendMetrics } // NewMessageBackend returns a new HybridBackend instance @@ -38,6 +38,7 @@ func NewHybridBackend(offloadLimit int, metadataPathFunc MetadataPathFunc, o cac offloadLimit: offloadLimit, metaCache: cache.GetFileMetadataCache(o), metadataPathFunc: metadataPathFunc, + metrics: newBackendMetrics("hybrid"), } } @@ -46,6 +47,7 @@ func (HybridBackend) Name() string { return "hybrid" } // IdentifyPath returns the space id, node id and mtime of a file func (b HybridBackend) IdentifyPath(_ context.Context, path string) (string, string, string, time.Time, error) { + b.metrics.reads.Inc() spaceID, err := xattr.Get(path, prefixes.SpaceIDAttr) if err != nil { if IsNotExist(err) { @@ -66,10 +68,13 @@ func (b HybridBackend) IdentifyPath(_ context.Context, path string) (string, str func (b HybridBackend) Get(ctx context.Context, n MetadataNode, key string) ([]byte, error) { attribs := map[string][]byte{} err := b.metaCache.PullFromCache(b.cacheKey(n), &attribs) - if err == nil && len(attribs[key]) > 0 { + found := err == nil && len(attribs[key]) > 0 + b.metrics.cacheLookup(found) + if found { return attribs[key], err } + b.metrics.reads.Inc() if isOffloadingAttribute(key) { // check if key is offloaded offloaded, err := xattr.Get(n.InternalPath(), metadataOffloadedAttr()) @@ -122,6 +127,7 @@ func (b HybridBackend) All(ctx context.Context, n MetadataNode) (map[string][]by attribs := map[string][]byte{} err := b.metaCache.PullFromCache(b.cacheKey(n), &attribs) + b.metrics.cacheLookup(err == nil) if err == nil { return attribs, err } @@ -138,6 +144,7 @@ func (b HybridBackend) All(ctx context.Context, n MetadataNode) (map[string][]by } func (b HybridBackend) getAll(ctx context.Context, n MetadataNode, skipOffloaded bool) (map[string][]byte, error) { + b.metrics.reads.Inc() attribs := map[string][]byte{} attrNames, err := b.list(ctx, n) if err != nil { @@ -217,6 +224,8 @@ func (b HybridBackend) SetMultiple(ctx context.Context, n MetadataNode, attribs defer func() { _ = unlock() }() } + // counts once together with reading the offloaded metadata below + b.metrics.reads.Inc() offloadAttr, err := xattr.Get(path, metadataOffloadedAttr()) offloaded := err == nil && string(offloadAttr) == "1" @@ -254,6 +263,7 @@ func (b HybridBackend) SetMultiple(ctx context.Context, n MetadataNode, attribs } } + b.metrics.writes.Inc() if offloaded { metaPath := b.MetadataPath(n) var msgBytes []byte @@ -340,6 +350,7 @@ func (b HybridBackend) offloadMetadata(ctx context.Context, n MetadataNode) erro return err } + b.metrics.writes.Inc() err = renameio.WriteFile(b.MetadataPath(n), d, 0600) if err != nil { return err @@ -376,6 +387,7 @@ func (b HybridBackend) Remove(ctx context.Context, n MetadataNode, key string) e } if isOffloadingAttribute(key) { + b.metrics.reads.Inc() offloadAttr, err := xattr.Get(path, metadataOffloadedAttr()) offloaded := err == nil && string(offloadAttr) == "1" if offloaded { @@ -412,12 +424,14 @@ func (b HybridBackend) Remove(ctx context.Context, n MetadataNode, key string) e return err } + b.metrics.writes.Inc() err = renameio.WriteFile(b.MetadataPath(n), d, 0600) if err != nil { return err } } else { // remove from xattrs + b.metrics.writes.Inc() err := xattr.Remove(path, key) if err != nil { return err @@ -425,6 +439,7 @@ func (b HybridBackend) Remove(ctx context.Context, n MetadataNode, key string) e } } else { // remove from xattrs + b.metrics.writes.Inc() err := xattr.Remove(path, key) if err != nil { return err @@ -452,6 +467,7 @@ func (b HybridBackend) Purge(ctx context.Context, n MetadataNode) error { attribs, err := b.getAll(ctx, n, false) if err == nil { + b.metrics.writes.Inc() for attr := range attribs { if strings.HasPrefix(attr, prefixes.OcPrefix) { _ = xattr.Remove(path, attr) @@ -497,7 +513,7 @@ func (b HybridBackend) Lock(n MetadataNode) (UnlockFunc, error) { } metaLockPath := b.LockfilePath(n) - mlock, err := lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) + mlock, err := lockFile(n, metaLockPath, os.O_RDWR|os.O_CREATE, b.metrics) if err != nil { if errors.Is(err, os.ErrNotExist) { // The lock file's parent directories don't exist yet (or anymore). @@ -517,7 +533,7 @@ func (b HybridBackend) Lock(n MetadataNode) (UnlockFunc, error) { return nil, err } } - mlock, err = lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) + mlock, err = lockFile(n, metaLockPath, os.O_RDWR|os.O_CREATE, b.metrics) if err != nil { return nil, err } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/lock.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/lock.go new file mode 100644 index 0000000000..ac2122af7e --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/lock.go @@ -0,0 +1,46 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package metadata + +import ( + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rogpeppe/go-internal/lockedfile" +) + +// lockFile opens and locks the lock file of a node like lockedfile.OpenFile, recording in the metrics how long +// it waits for the lock and, once the returned lock is closed, how long the lock has been held +func lockFile(n MetadataNode, path string, flag int, m *backendMetrics) (*heldLock, error) { + lm := m.locks(n) + + m.locksWaiting.Inc() + start := time.Now() + f, err := lockedfile.OpenFile(path, flag, 0600) + m.locksWaiting.Dec() + if err != nil { + return nil, err + } + locked := time.Now() + lm.wait.Observe(locked.Sub(start).Seconds()) + return &heldLock{f: f, held: lm.held, since: locked}, nil +} + +// heldLock is a locked lock file +type heldLock struct { + f *lockedfile.File + held prometheus.Observer + since time.Time + closed bool +} + +// Close unlocks and closes the lock file. Only the first call records how long the lock has been held: callers +// may unlock explicitly and again in a defer, and the lock is no longer held by then. +func (l *heldLock) Close() error { + if !l.closed { + l.closed = true + l.held.Observe(time.Since(l.since).Seconds()) + } + return l.f.Close() +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go index af719f4ac1..3ab894c39d 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/messagepack_backend.go @@ -33,7 +33,6 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/cache" "github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/prefixes" "github.com/pkg/xattr" - "github.com/rogpeppe/go-internal/lockedfile" "github.com/vmihailenco/msgpack/v5" "go.opentelemetry.io/otel/codes" ) @@ -41,12 +40,14 @@ import ( // MessagePackBackend persists the attributes in messagepack format inside the file type MessagePackBackend struct { metaCache cache.FileMetadataCache + metrics *backendMetrics } // NewMessagePackBackend returns a new MessagePackBackend instance func NewMessagePackBackend(o cache.Config) MessagePackBackend { return MessagePackBackend{ metaCache: cache.GetFileMetadataCache(o), + metrics: newBackendMetrics("messagepack"), } } @@ -56,6 +57,7 @@ func (MessagePackBackend) Name() string { return "messagepack" } // IdentifyPath returns the id and mtime of a file func (b MessagePackBackend) IdentifyPath(_ context.Context, path string) (string, string, string, time.Time, error) { metaPath := filepath.Clean(path + ".mpk") + b.metrics.reads.Inc() source, err := os.Open(metaPath) // // No cached entry found. Read from storage and store in cache if err != nil { @@ -157,6 +159,7 @@ func (b MessagePackBackend) saveAttributes(ctx context.Context, n MetadataNode, defer func() { _ = unlock() }() } // Read current state + b.metrics.reads.Inc() _, subspan := tracer.Start(ctx, "os.ReadFile") var msgBytes []byte msgBytes, err = os.ReadFile(metaPath) @@ -192,6 +195,7 @@ func (b MessagePackBackend) saveAttributes(ctx context.Context, n MetadataNode, } // overwrite file atomically + b.metrics.writes.Inc() _, subspan = tracer.Start(ctx, "renameio.Writefile") err = renameio.WriteFile(metaPath, d, 0600) if err != nil { @@ -210,6 +214,7 @@ func (b MessagePackBackend) loadAttributes(ctx context.Context, n MetadataNode) defer span.End() attribs := map[string][]byte{} err := b.metaCache.PullFromCache(b.cacheKey(n), &attribs) + b.metrics.cacheLookup(err == nil) if err == nil { return attribs, err } @@ -217,6 +222,7 @@ func (b MessagePackBackend) loadAttributes(ctx context.Context, n MetadataNode) metaPath := b.MetadataPath(n) // No cached entry found. Read from storage and store in cache + b.metrics.reads.Inc() _, subspan := tracer.Start(ctx, "os.Open") source, err := os.Open(metaPath) subspan.End() @@ -271,6 +277,7 @@ func (b MessagePackBackend) Purge(_ context.Context, n MetadataNode) error { return err } + b.metrics.writes.Inc() return os.Remove(b.MetadataPath(n)) } @@ -289,6 +296,7 @@ func (b MessagePackBackend) Rename(oldNode, newNode MetadataNode) error { return err } + b.metrics.writes.Inc() return os.Rename(b.MetadataPath(oldNode), b.MetadataPath(newNode)) } @@ -305,7 +313,7 @@ func (b MessagePackBackend) Lock(n MetadataNode) (UnlockFunc, error) { } metaLockPath := b.LockfilePath(n) - mlock, err := lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) + mlock, err := lockFile(n, metaLockPath, os.O_RDWR|os.O_CREATE, b.metrics) if err != nil { return nil, err } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/metrics.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/metrics.go new file mode 100644 index 0000000000..ee50ae29d6 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/metrics.go @@ -0,0 +1,92 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package metadata + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +// the metrics of the backends, by the name of the backend, see backendMetrics. A read or write of the +// metadata of a node counts once, however many attributes or files it involves. +var ( + reads = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_metadata_reads_total", + Help: "Number of times the metadata of a node has been read from the filesystem", + }, []string{"backend"}) + writes = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_metadata_writes_total", + Help: "Number of times the metadata of a node has been written to the filesystem", + }, []string{"backend"}) + cacheLookups = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_metadata_cache_lookups_total", + Help: "Number of times the metadata of a node has been looked up in the cache, by whether it has been found (result hit) or not (result miss)", + }, []string{"backend", "result"}) + locksWaiting = promauto.NewGaugeVec(prometheus.GaugeOpts{ + Name: "reva_metadata_lock_waiting", + Help: "Number of metadata locks being waited for", + }, []string{"backend"}) + lockWait = promauto.NewHistogramVec(prometheus.HistogramOpts{ + Name: "reva_metadata_lock_wait_seconds", + Help: "Time spent waiting for metadata locks, by whether the node is a space root", + Buckets: prometheus.ExponentialBuckets(.0001, 4, 10), + }, []string{"backend", "space_root"}) + lockHeld = promauto.NewHistogramVec(prometheus.HistogramOpts{ + Name: "reva_metadata_lock_held_seconds", + Help: "Time metadata locks have been held, by whether the node is a space root", + Buckets: prometheus.ExponentialBuckets(.0001, 4, 10), + }, []string{"backend", "space_root"}) +) + +// backendMetrics are the metrics of a backend +type backendMetrics struct { + reads prometheus.Counter + writes prometheus.Counter + cacheHits prometheus.Counter + cacheMisses prometheus.Counter + locksWaiting prometheus.Gauge + // the locks of space roots are the ones every propagation in a space ends at + spaceRootLocks lockMetrics + otherLocks lockMetrics +} + +type lockMetrics struct { + wait prometheus.Observer + held prometheus.Observer +} + +func newBackendMetrics(backend string) *backendMetrics { + return &backendMetrics{ + reads: reads.WithLabelValues(backend), + writes: writes.WithLabelValues(backend), + cacheHits: cacheLookups.WithLabelValues(backend, "hit"), + cacheMisses: cacheLookups.WithLabelValues(backend, "miss"), + locksWaiting: locksWaiting.WithLabelValues(backend), + spaceRootLocks: lockMetrics{ + wait: lockWait.WithLabelValues(backend, "true"), + held: lockHeld.WithLabelValues(backend, "true"), + }, + otherLocks: lockMetrics{ + wait: lockWait.WithLabelValues(backend, "false"), + held: lockHeld.WithLabelValues(backend, "false"), + }, + } +} + +// cacheLookup counts a lookup in the cache +func (m *backendMetrics) cacheLookup(found bool) { + if found { + m.cacheHits.Inc() + } else { + m.cacheMisses.Inc() + } +} + +// locks returns the lock metrics for the locks of a node +func (m *backendMetrics) locks(n MetadataNode) lockMetrics { + if id := n.GetID(); id != "" && id == n.GetSpaceID() { + return m.spaceRootLocks + } + return m.otherLocks +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go index 0111a72a23..629072b448 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/metadata/xattrs_backend.go @@ -31,18 +31,19 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks" "github.com/pkg/errors" "github.com/pkg/xattr" - "github.com/rogpeppe/go-internal/lockedfile" ) // XattrsBackend stores the file attributes in extended attributes type XattrsBackend struct { metaCache cache.FileMetadataCache + metrics *backendMetrics } // NewMessageBackend returns a new XattrsBackend instance func NewXattrsBackend(o cache.Config) XattrsBackend { return XattrsBackend{ metaCache: cache.GetFileMetadataCache(o), + metrics: newBackendMetrics("xattrs"), } } @@ -51,6 +52,7 @@ func (XattrsBackend) Name() string { return "xattrs" } // IdentifyPath returns the space id, node id and mtime of a file func (b XattrsBackend) IdentifyPath(_ context.Context, path string) (string, string, string, time.Time, error) { + b.metrics.reads.Inc() spaceID, _ := xattr.Get(path, prefixes.SpaceIDAttr) id, _ := xattr.Get(path, prefixes.IDAttr) parentID, _ := xattr.Get(path, prefixes.ParentidAttr) @@ -66,10 +68,13 @@ func (b XattrsBackend) IdentifyPath(_ context.Context, path string) (string, str func (b XattrsBackend) Get(ctx context.Context, n MetadataNode, key string) ([]byte, error) { attribs := map[string][]byte{} err := b.metaCache.PullFromCache(b.cacheKey(n), &attribs) - if err == nil && len(attribs[key]) > 0 { + found := err == nil && len(attribs[key]) > 0 + b.metrics.cacheLookup(found) + if found { return attribs[key], err } + b.metrics.reads.Inc() return xattr.Get(n.InternalPath(), key) } @@ -102,7 +107,7 @@ func (b XattrsBackend) list(ctx context.Context, n MetadataNode, acquireLock boo // listing xattrs failed, try again, either with lock or without if acquireLock { - f, err := lockedfile.OpenFile(filePath+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, 0600) + f, err := lockFile(n, filePath+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, b.metrics) if err != nil { return nil, err } @@ -128,11 +133,13 @@ func (b XattrsBackend) getAll(ctx context.Context, n MetadataNode, skipCache, ac if !skipCache { err := b.metaCache.PullFromCache(b.cacheKey(n), &attribs) + b.metrics.cacheLookup(err == nil) if err == nil { return attribs, err } } + b.metrics.reads.Inc() attrNames, err := b.list(ctx, n, acquireLock) if err != nil { return nil, err @@ -184,7 +191,7 @@ func (b XattrsBackend) SetMultiple(ctx context.Context, n MetadataNode, attribs if err != nil { return err } - lockedFile, err := lockedfile.OpenFile(b.LockfilePath(n), os.O_CREATE|os.O_WRONLY, 0600) + lockedFile, err := lockFile(n, b.LockfilePath(n), os.O_CREATE|os.O_WRONLY, b.metrics) if err != nil { return err } @@ -202,6 +209,7 @@ func (b XattrsBackend) SetMultiple(ctx context.Context, n MetadataNode, attribs xerrs = 0 xerr error ) + b.metrics.writes.Inc() for key, val := range attribs { if xerr = xattr.Set(path, key, val); xerr != nil { // log @@ -223,7 +231,7 @@ func (b XattrsBackend) SetMultiple(ctx context.Context, n MetadataNode, attribs func (b XattrsBackend) Remove(ctx context.Context, n MetadataNode, key string) error { path := n.InternalPath() if !n.LockHeld() { - lockedFile, err := lockedfile.OpenFile(path+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, 0600) + lockedFile, err := lockFile(n, path+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, b.metrics) if err != nil { return err } @@ -235,6 +243,7 @@ func (b XattrsBackend) Remove(ctx context.Context, n MetadataNode, key string) e }() } + b.metrics.writes.Inc() err := xattr.Remove(path, key) if err != nil { return err @@ -259,6 +268,7 @@ func (b XattrsBackend) Purge(ctx context.Context, n MetadataNode) error { return err } + b.metrics.writes.Inc() for attr := range attribs { if strings.HasPrefix(attr, prefixes.OcPrefix) { err := xattr.Remove(path, attr) @@ -298,7 +308,7 @@ func (b XattrsBackend) Lock(n MetadataNode) (UnlockFunc, error) { } metaLockPath := b.LockfilePath(n) - mlock, err := lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) + mlock, err := lockFile(n, metaLockPath, os.O_RDWR|os.O_CREATE, b.metrics) if err != nil { return nil, err } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go index 79f6623371..4c775d2201 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/node/node.go @@ -40,6 +40,7 @@ import ( "github.com/google/uuid" "github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider" "github.com/opencloud-eu/reva/v2/pkg/appctx" + "github.com/opencloud-eu/reva/v2/pkg/conversions" ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/mime" @@ -952,8 +953,8 @@ func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissi // share indicator if _, ok := fieldMaskKeysMap["share-types"]; returnAllFields || ok { - granteeTypes := n.getGranteeTypes(ctx) - if len(granteeTypes) > 0 { + granteeTypes, hasGuestShares := n.getGranteeTypes(ctx) + if len(granteeTypes) > 0 || hasGuestShares { // TODO add optional property to CS3 ResourceInfo to transport grants? var s strings.Builder first := true @@ -965,6 +966,12 @@ func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissi } s.WriteString(strconv.Itoa(int(t))) } + if hasGuestShares { + if !first { + s.WriteString(",") + } + s.WriteString(strconv.Itoa(int(conversions.ShareTypeGuest))) + } ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "share-types", s.String()) } } @@ -1369,17 +1376,25 @@ func (n *Node) ListGrants(ctx context.Context) ([]*provider.Grant, error) { return grants, nil } -func (n *Node) getGranteeTypes(ctx context.Context) []provider.GranteeType { +// getGranteeTypes returns the grantee types of the node's grants. The second +// return value reports whether the node has guest shares, which are stored as +// user grants with a mail ACE prefix. +func (n *Node) getGranteeTypes(ctx context.Context) ([]provider.GranteeType, bool) { types := []provider.GranteeType{} + hasGuestShares := false if g, err := n.ListGrantees(ctx); err == nil { hasUserShares, hasGroupShares := false, false for i := range g { switch { - case !hasUserShares && (strings.HasPrefix(g[i], prefixes.GrantUserAcePrefix) || strings.HasPrefix(g[i], prefixes.GrantMailAcePrefix)): + case !hasGuestShares && strings.HasPrefix(g[i], prefixes.GrantMailAcePrefix): + hasGuestShares = true + case !hasUserShares && strings.HasPrefix(g[i], prefixes.GrantUserAcePrefix): hasUserShares = true case !hasGroupShares && strings.HasPrefix(g[i], prefixes.GrantGroupAcePrefix): hasGroupShares = true - case hasUserShares && hasGroupShares: + } + + if hasUserShares && hasGroupShares && hasGuestShares { break } } @@ -1390,7 +1405,7 @@ func (n *Node) getGranteeTypes(ctx context.Context) []provider.GranteeType { types = append(types, provider.GranteeType_GRANTEE_TYPE_GROUP) } } - return types + return types, hasGuestShares } // ancestorGrants returns the active grants on the node and all its ancestors. The grants on the diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/options/options.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/options/options.go index f2827eccc2..9b785a1b53 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/options/options.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/options/options.go @@ -45,9 +45,9 @@ type Options struct { // the attribute key prefix of the metadata on disk, process wide, see prefixes.SetOcPrefix MetadataPrefix string `mapstructure:"metadata_prefix"` - // the propagator to use for this fs. currently only `sync` is fully supported, `async` is available as an experimental feature + // the propagator to use for this fs. currently only `sync` is fully supported, `async` is deprecated and will be removed in a future release Propagator string `mapstructure:"propagator"` - // Options specific to the async propagator + // Options specific to the async propagator, which is deprecated AsyncPropagatorOptions AsyncPropagatorOptions `mapstructure:"async_propagator_options"` // decomposedfs fs works on top of a dir of uuid nodes diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go index 0815a403dd..8a7018d184 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/recycle.go @@ -361,6 +361,9 @@ func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, spaceID rn, parent, restoreFunc, err := tb.fs.tp.(*tree.Tree).RestoreRecycleItemFunc(ctx, spaceID, key, relativePath, targetNode) if err != nil { + if errors.Is(err, iofs.ErrNotExist) { + return nil, errtypes.NotFound(key) + } return nil, err } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go index 112fc147cf..99441e6794 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/spaces.go @@ -778,6 +778,26 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De return errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space")) } + // delete the blobs of all nodes first, so that a failed purge can be retried + // https://github.com/opencloud-eu/opencloud/issues/1865 + // NOTE: This isn't needed when no s3 is used, but we can't differentiate that here... + spaceRoot := fs.lu.InternalSpaceRoot(spaceID) + if spaceRoot != "" { + err := filepath.Walk(spaceRoot, func(path string, info os.FileInfo, err error) error { + // skip child symlinks, e.g. of a user file named backup.mpk + if err == nil && info.Mode().IsRegular() && filepath.Ext(path) == ".mpk" { + err = fs.deleteBlobOf(ctx, spaceID, path) + } + if os.IsNotExist(err) { + return nil + } + return err + }) + if err != nil { + return err + } + } + spaceType, err := n.XattrString(ctx, prefixes.SpaceTypeAttr) if err != nil { return err @@ -834,50 +854,7 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De root := n.InternalPath() - // walkfn will delete the blob if the node has one - walkfn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if filepath.Ext(path) != ".mpk" { - return nil - } - - b, err := os.ReadFile(path) - if err != nil { - return err - } - - m := map[string][]byte{} - if err := msgpack.Unmarshal(b, &m); err != nil { - return err - } - - bid := m["user.oc.blobid"] - if string(bid) == "" { - return nil - } - - if err := fs.tp.DeleteBlob(&node.Node{ - BaseNode: node.BaseNode{SpaceID: spaceID}, - BlobID: string(bid), - }); err != nil { - return err - } - - // remove .mpk file so subsequent attempts will not try to delete the blob again - return os.Remove(path) - } - - // This is deletes all blobs of the space - // NOTE: This isn't needed when no s3 is used, but we can't differentiate that here... - if err := filepath.Walk(root, walkfn); err != nil { - return err - } - // remove space metadata - spaceRoot := fs.lu.InternalSpaceRoot(spaceID) if spaceRoot != "" { if err := removeSpaceRoot(spaceRoot); err != nil { return err @@ -1220,6 +1197,27 @@ func isGrantExpired(g *provider.Grant) bool { return time.Now().After(time.Unix(int64(g.Expiration.Seconds), int64(g.Expiration.Nanos))) } +// deleteBlobOf deletes the blob referenced by the metadata file at path, then the file itself +func (fs *Decomposedfs) deleteBlobOf(ctx context.Context, spaceID, path string) error { + b, err := os.ReadFile(path) + if err != nil { + return err + } + m := map[string][]byte{} + if err := msgpack.Unmarshal(b, &m); err != nil { + appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", spaceID).Str("path", path).Msg("could not parse metadata, skipping") + return nil + } + bid := string(m[prefixes.BlobIDAttr]) + if bid == "" { + return nil + } + if err := fs.tp.DeleteBlob(&node.Node{BaseNode: node.BaseNode{SpaceID: spaceID}, BlobID: bid}); err != nil { + return err + } + return os.Remove(path) +} + // removeSpaceRoot moves the space root out of the way before deleting it. Concurrent requests may // still lock nodes of the space and recreate lock files inside it, which makes an in-place // RemoveAll fail with "directory not empty". Once the space root is gone they can't do that anymore. diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/async.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/async.go index 5348b620c7..76a930388a 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/async.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/async.go @@ -44,6 +44,8 @@ const ( var _propagationGracePeriod = 3 * time.Minute // AsyncPropagator implements asynchronous treetime & treesize propagation +// +// Deprecated: the async propagator will be removed in a future release. Use the sync propagator instead. type AsyncPropagator struct { treeSizeAccounting bool treeTimeAccounting bool @@ -59,6 +61,8 @@ type Change struct { } // NewAsyncPropagator returns a new AsyncPropagator instance +// +// Deprecated: the async propagator will be removed in a future release. Use the sync propagator instead. func NewAsyncPropagator(treeSizeAccounting, treeTimeAccounting bool, o options.AsyncPropagatorOptions, lookup node.PathLookup, log *zerolog.Logger) AsyncPropagator { p := AsyncPropagator{ treeSizeAccounting: treeSizeAccounting, @@ -69,6 +73,7 @@ func NewAsyncPropagator(treeSizeAccounting, treeTimeAccounting bool, o options.A } log.Info().Msg("async propagator starting up...") + log.Warn().Msg("the async propagator is deprecated and will be removed in a future release, please switch to the sync propagator") // spawn a goroutine that watches for stale .processing dirs and fixes them go func() { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/metrics.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/metrics.go new file mode 100644 index 0000000000..c60d5cf885 --- /dev/null +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/metrics.go @@ -0,0 +1,40 @@ +// Copyright 2026 OpenCloud GmbH +// SPDX-License-Identifier: Apache-2.0 + +package propagator + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +// the metrics of the propagation, by the internal root of the storage, see metrics +var ( + queuedChanges = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_propagation_changes_total", + Help: "Number of changes to be propagated", + }, []string{"root"}) + directoryUpdates = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_propagation_directory_updates_total", + Help: "Number of directory updates written by the propagation", + }, []string{"root"}) + failures = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "reva_propagation_failures_total", + Help: "Number of failed attempts to apply changes to a directory", + }, []string{"root"}) +) + +// metrics are the metrics of a propagator +type metrics struct { + changes prometheus.Counter + updates prometheus.Counter + failures prometheus.Counter +} + +func newMetrics(internalRoot string) metrics { + return metrics{ + changes: queuedChanges.WithLabelValues(internalRoot), + updates: directoryUpdates.WithLabelValues(internalRoot), + failures: failures.WithLabelValues(internalRoot), + } +} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/sync.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/sync.go index 99aed8eefe..ebfb077970 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/sync.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/tree/propagator/sync.go @@ -35,6 +35,7 @@ type SyncPropagator struct { treeSizeAccounting bool treeTimeAccounting bool lookup node.PathLookup + metrics metrics } // NewSyncPropagator returns a new AsyncPropagator instance @@ -43,6 +44,7 @@ func NewSyncPropagator(treeSizeAccounting, treeTimeAccounting bool, lookup node. treeSizeAccounting: treeSizeAccounting, treeTimeAccounting: treeTimeAccounting, lookup: lookup, + metrics: newMetrics(lookup.InternalRoot()), } } @@ -62,6 +64,7 @@ func (p SyncPropagator) Propagate(ctx context.Context, n *node.Node, sizeDiff in sublog.Debug().Msg("propagation disabled or nothing to propagate") return nil } + p.metrics.changes.Inc() // is propagation enabled for the parent node? root := n.SpaceRoot @@ -80,6 +83,7 @@ func (p SyncPropagator) Propagate(ctx context.Context, n *node.Node, sizeDiff in } if err != nil { + p.metrics.failures.Inc() sublog.Error().Err(err).Msg("error propagating") return err } @@ -195,6 +199,7 @@ func (p SyncPropagator) propagateItem(ctx context.Context, n *node.Node, sTime t log.Error().Err(err).Msg("Failed to update extend attributes of parent node") return n, true, err } + p.metrics.updates.Inc() return n, false, nil } diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects/aspects.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects/aspects.go deleted file mode 100644 index 7f6d91a227..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects/aspects.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2018-2024 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package aspects - -import ( - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper" -) - -// Aspects holds dependencies for handling aspects of the decomposedfs -type Aspects struct { - Lookup node.PathLookup - Tree node.Tree - Trashbin trashbin.Trashbin - Permissions permissions.Permissions - EventStream events.Stream - DisableVersioning bool - UserMapper usermapper.Mapper -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/decomposedfs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/decomposedfs.go deleted file mode 100644 index 08b9bf089d..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/decomposedfs.go +++ /dev/null @@ -1,1359 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "fmt" - "io" - "math" - "net/url" - "path" - "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" - "github.com/pkg/errors" - "github.com/rs/zerolog" - tusd "github.com/tus/tusd/v2/pkg/handler" - microstore "go-micro.dev/v4/store" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" - "golang.org/x/sync/errgroup" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/templates" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/store" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -type CtxKey int - -const ( - CtxKeySpaceGID CtxKey = iota -) - -var ( - tracer trace.Tracer - - _registeredEvents = []events.Unmarshaller{ - events.PostprocessingFinished{}, - events.PostprocessingStepFinished{}, - events.RestartPostprocessing{}, - events.CleanUpload{}, - events.DeleteRevision{}, - } -) - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs") -} - -// Session is the interface that OcisSession implements. By combining tus.Upload, -// storage.UploadSession and custom functions we can reuse the same struct throughout -// the whole upload lifecycle. -// -// Some functions that are only used by decomposedfs are not yet part of this interface. -// They might be added after more refactoring. -type Session interface { - tusd.Upload - storage.UploadSession - upload.Session - LockID() string -} - -type SessionStore interface { - New(ctx context.Context) *upload.OcisSession - List(ctx context.Context) ([]*upload.OcisSession, error) - Get(ctx context.Context, id string) (*upload.OcisSession, error) -} - -// Decomposedfs provides the base for decomposed filesystem implementations -type Decomposedfs struct { - lu node.PathLookup - tp node.Tree - trashbin trashbin.Trashbin - o *options.Options - p permissions.Permissions - um usermapper.Mapper - chunkHandler *chunking.ChunkHandler - stream events.Stream - sessionStore SessionStore - - UserCache *ttlcache.Cache - userSpaceIndex *spaceidindex.Index - groupSpaceIndex *spaceidindex.Index - spaceTypeIndex *spaceidindex.Index - - log *zerolog.Logger -} - -// NewDefault returns an instance with default components -func NewDefault(m map[string]interface{}, bs tree.Blobstore, es events.Stream, log *zerolog.Logger) (storage.FS, error) { - if log == nil { - log = &zerolog.Logger{} - } - - o, err := options.New(m) - if err != nil { - return nil, err - } - - var lu *lookup.Lookup - switch o.MetadataBackend { - case "xattrs": - lu = lookup.New(metadata.NewXattrsBackend(o.Root, o.FileMetadataCache), o, &timemanager.Manager{}) - case "messagepack": - lu = lookup.New(metadata.NewMessagePackBackend(o.Root, o.FileMetadataCache), o, &timemanager.Manager{}) - default: - return nil, fmt.Errorf("unknown metadata backend %s, only 'messagepack' or 'xattrs' (default) supported", o.MetadataBackend) - } - - tp := tree.New(lu, bs, o, store.Create( - store.Store(o.IDCache.Store), - store.TTL(o.IDCache.TTL), - store.Size(o.IDCache.Size), - microstore.Nodes(o.IDCache.Nodes...), - microstore.Database(o.IDCache.Database), - microstore.Table(o.IDCache.Table), - store.DisablePersistence(o.IDCache.DisablePersistence), - store.Authentication(o.IDCache.AuthUsername, o.IDCache.AuthPassword), - store.TLSEnabled(o.IDCache.TLSEnabled), - store.TLSInsecure(o.IDCache.TLSInsecure), - store.TLSRootCA(o.IDCache.TLSRootCACertificate), - ), log) - - permissionsSelector, err := pool.PermissionsSelector(o.PermissionsSVC, pool.WithTLSMode(o.PermTLSMode)) - if err != nil { - return nil, err - } - - aspects := aspects.Aspects{ - Lookup: lu, - Tree: tp, - Permissions: permissions.NewPermissions(node.NewPermissions(lu), permissionsSelector), - EventStream: es, - DisableVersioning: o.DisableVersioning, - Trashbin: &DecomposedfsTrashbin{}, - } - - return New(o, aspects, log) -} - -// New returns an implementation of the storage.FS interface that talks to -// a local filesystem. -func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (storage.FS, error) { - if log == nil { - log = &zerolog.Logger{} - } - - err := aspects.Tree.Setup() - if err != nil { - log.Error().Err(err).Msg("could not setup tree") - return nil, errors.Wrap(err, "could not setup tree") - } - - // Run migrations & return - m := migrator.New(aspects.Lookup, log) - err = m.RunMigrations() - if err != nil { - log.Error().Err(err).Msg("could not migrate tree") - return nil, errors.Wrap(err, "could not migrate tree") - } - - if o.MaxAcquireLockCycles != 0 { - filelocks.SetMaxLockCycles(o.MaxAcquireLockCycles) - } - - if o.LockCycleDurationFactor != 0 { - filelocks.SetLockCycleDurationFactor(o.LockCycleDurationFactor) - } - userSpaceIndex := spaceidindex.New(filepath.Join(o.Root, "indexes"), "by-user-id") - err = userSpaceIndex.Init() - if err != nil { - return nil, err - } - groupSpaceIndex := spaceidindex.New(filepath.Join(o.Root, "indexes"), "by-group-id") - err = groupSpaceIndex.Init() - if err != nil { - return nil, err - } - spaceTypeIndex := spaceidindex.New(filepath.Join(o.Root, "indexes"), "by-type") - err = spaceTypeIndex.Init() - if err != nil { - return nil, err - } - - if aspects.Trashbin == nil { - return nil, errors.New("need trashbin") - } - // set a null usermapper if we don't have one - if aspects.UserMapper == nil { - aspects.UserMapper = &usermapper.NullMapper{} - } - - fs := &Decomposedfs{ - tp: aspects.Tree, - lu: aspects.Lookup, - trashbin: aspects.Trashbin, - o: o, - p: aspects.Permissions, - um: aspects.UserMapper, - chunkHandler: chunking.NewChunkHandler(filepath.Join(o.Root, "uploads")), - stream: aspects.EventStream, - UserCache: ttlcache.NewCache(), - userSpaceIndex: userSpaceIndex, - groupSpaceIndex: groupSpaceIndex, - spaceTypeIndex: spaceTypeIndex, - log: log, - } - fs.sessionStore = upload.NewSessionStore(fs, aspects, o.Root, o.AsyncFileUploads, o.Tokens, log) - if err = fs.trashbin.Setup(fs); err != nil { - return nil, err - } - - 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, "dcfs", _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) - } - } - - return fs, nil -} - -// Postprocessing starts the postprocessing result collector -func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) { - for event := range ch { - // derive a per-event context from the event's W3C trace context so the - // postprocessing work is linked to the originating request - ctx := event.GetTraceContext(context.Background()) - ctx = ctxpkg.ContextSetInitiator(ctx, event.InitiatorID) - fs.handlePostprocessingEvent(ctx, event) - } -} - -// handlePostprocessingEvent processes a single postprocessing event under a span -// scoped to that event's trace context. -func (fs *Decomposedfs) handlePostprocessingEvent(ctx context.Context, event events.Event) { - ctx, span := tracer.Start(ctx, "Postprocessing/"+event.Type) - defer span.End() - log := fs.log - switch ev := event.Event.(type) { - case events.PostprocessingFinished: - sublog := log.With().Str("event", "PostprocessingFinished").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 - } - - 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.DeleteRevision: - sublog := log.With().Str("event", "DeleteRevision").Interface("nodeid", ev.ResourceID).Logger() - n, err := fs.lu.NodeFromID(ctx, ev.ResourceID) - if err != nil { - sublog.Error().Err(err).Msg("Failed to get node") - return - } - - var deleteErr error - if ev.Timestamp == nil { - // the node's current revision is targeted - revert to the pre-upload - // state. Only stuck nodes are targeted: a reverted node has its - // processing flag removed, so a redelivered event is a no-op. - if !n.IsProcessing(ctx) { - sublog.Debug().Msg("node is not stuck, ignoring") - return - } - _, deleteErr = n.DeleteRevision(ctx, "") - } else { - versionID := time.Unix(int64(ev.Timestamp.Seconds), int64(ev.Timestamp.Nanos)).UTC().Format(time.RFC3339Nano) - deleteErr = fs.deleteRevisionFile(ctx, n, n.ID+node.RevisionIDDelimiter+versionID) - } - if deleteErr != nil { - sublog.Error().Err(deleteErr).Msg("Failed to delete revision") - } - case events.PostprocessingStepFinished: - sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger() - 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") - } -} - -// Shutdown shuts down the storage -func (fs *Decomposedfs) Shutdown(ctx context.Context) error { - return nil -} - -// GetQuota returns the quota available -// TODO Document in the cs3 should we return quota or free space? -func (fs *Decomposedfs) GetQuota(ctx context.Context, ref *provider.Reference) (total uint64, inUse uint64, remaining uint64, err error) { - ctx, span := tracer.Start(ctx, "GetQuota") - defer span.End() - var n *node.Node - if ref == nil { - err = errtypes.BadRequest("no space given") - return 0, 0, 0, err - } - if n, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return 0, 0, 0, err - } - - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return 0, 0, 0, err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return 0, 0, 0, err - case !rp.GetQuota && !fs.p.ListAllSpaces(ctx): - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return 0, 0, 0, errtypes.PermissionDenied(f) - } - return 0, 0, 0, errtypes.NotFound(f) - } - - // FIXME move treesize & quota to fieldmask - ri, err := n.AsResourceInfo(ctx, rp, []string{"treesize", "quota"}, []string{}, true) - if err != nil { - return 0, 0, 0, err - } - - quotaStr := node.QuotaUnknown - if ri.Opaque != nil && ri.Opaque.Map != nil && ri.Opaque.Map["quota"] != nil && ri.Opaque.Map["quota"].Decoder == "plain" { - quotaStr = string(ri.Opaque.Map["quota"].Value) - } - - return fs.calculateTotalUsedRemaining(quotaStr, ri.Size) -} - -func (fs *Decomposedfs) calculateTotalUsedRemaining(quotaStr string, inUse uint64) (uint64, uint64, uint64, error) { - var err error - var total uint64 - - remaining := uint64(math.MaxUint64) - switch quotaStr { - case node.QuotaUncalculated, node.QuotaUnknown: - // best we can do is return current total - // TODO indicate unlimited total? -> in opaque data? - case node.QuotaUnlimited: - total = 0 - default: - total, err = strconv.ParseUint(quotaStr, 10, 64) - if err != nil { - return 0, 0, 0, err - } - - switch { - case total > inUse: - remaining = total - inUse - case total <= inUse: - remaining = 0 - } - - } - return total, inUse, remaining, nil -} - -// CreateHome creates a new home node for the given user -func (fs *Decomposedfs) CreateHome(ctx context.Context) (err error) { - ctx, span := tracer.Start(ctx, "CreateHome") - defer span.End() - if fs.o.UserLayout == "" { - return errtypes.NotSupported("Decomposedfs: CreateHome() home supported disabled") - } - - u := ctxpkg.ContextMustGetUser(ctx) - res, err := fs.CreateStorageSpace(ctx, &provider.CreateStorageSpaceRequest{ - Type: _spaceTypePersonal, - Owner: u, - }) - if err != nil { - return err - } - if res.Status.Code != rpcv1beta1.Code_CODE_OK { - return errtypes.NewErrtypeFromStatus(res.Status) - } - return nil -} - -// GetHome is called to look up the home path for a user -// It is NOT supposed to return the internal path but the external path -func (fs *Decomposedfs) GetHome(ctx context.Context) (string, error) { - ctx, span := tracer.Start(ctx, "GetHome") - defer span.End() - if fs.o.UserLayout == "" { - return "", errtypes.NotSupported("Decomposedfs: GetHome() home supported disabled") - } - u := ctxpkg.ContextMustGetUser(ctx) - layout := templates.WithUser(u, fs.o.UserLayout) - return filepath.Join(fs.o.Root, layout), nil // TODO use a namespace? -} - -// GetPathByID returns the fn pointed by the file id, without the internal namespace -func (fs *Decomposedfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { - ctx, span := tracer.Start(ctx, "GetPathByID") - defer span.End() - n, err := fs.lu.NodeFromID(ctx, id) - if err != nil { - return "", err - } - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return "", err - case !rp.GetPath: - f := storagespace.FormatResourceID(id) - if rp.Stat { - return "", errtypes.PermissionDenied(f) - } - return "", errtypes.NotFound(f) - } - - hp := func(n *node.Node) bool { - perms, err := fs.p.AssemblePermissions(ctx, n) - if err != nil { - return false - } - return perms.GetPath - } - return fs.lu.Path(ctx, n, hp) -} - -// CreateDir creates the specified directory -func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { - ctx, span := tracer.Start(ctx, "CreateDir") - defer span.End() - - name := path.Base(ref.Path) - if name == "" || name == "." || name == "/" { - return errtypes.BadRequest("Invalid path: " + ref.Path) - } - - parentRef := &provider.Reference{ - ResourceId: ref.ResourceId, - Path: path.Dir(ref.Path), - } - - // verify parent exists - var n *node.Node - if n, err = fs.lu.NodeFromResource(ctx, parentRef); err != nil { - if e, ok := err.(errtypes.NotFound); ok { - return errtypes.PreconditionFailed(e.Error()) - } - return - } - // TODO check if user has access to root / space - if !n.Exists { - return errtypes.PreconditionFailed(parentRef.Path) - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return err - case !rp.CreateContainer: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - // check lock - if err := n.CheckLock(ctx); err != nil { - return err - } - - // verify child does not exist, yet - if n, err = n.Child(ctx, name); err != nil { - return - } - if n.Exists { - return errtypes.AlreadyExists(ref.Path) - } - - if err = fs.tp.CreateDir(ctx, n); err != nil { - return - } - - return -} - -// TouchFile as defined in the storage.FS interface -func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error { - ctx, span := tracer.Start(ctx, "TouchFile") - defer span.End() - parentRef := &provider.Reference{ - ResourceId: ref.ResourceId, - Path: path.Dir(ref.Path), - } - - // verify parent exists - parent, err := fs.lu.NodeFromResource(ctx, parentRef) - if err != nil { - return errtypes.InternalError(err.Error()) - } - if !parent.Exists { - return errtypes.NotFound(parentRef.Path) - } - - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errtypes.InternalError(err.Error()) - } - - // new file: check write permission on parent, not the not-yet-existing node - permNode := n - if !n.Exists { - permNode = parent - } - rp, err := fs.p.AssemblePermissions(ctx, permNode) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - // check lock - if err := n.CheckLock(ctx); err != nil { - return err - } - return fs.tp.TouchFile(ctx, n, markprocessing, mtime) -} - -// CreateReference creates a reference as a node folder with the target stored in extended attributes -// There is no difference between the /Shares folder and normal nodes because the storage is not supposed to be accessible -// without the storage provider. In effect everything is a shadow namespace. -// To mimic the eos and owncloud driver we only allow references as children of the "/Shares" folder -// FIXME: This comment should explain briefly what a reference is in this context. -func (fs *Decomposedfs) CreateReference(ctx context.Context, p string, targetURI *url.URL) (err error) { - return errtypes.NotSupported("not implemented") -} - -// Move moves a resource from one reference to another -func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) { - ctx, span := tracer.Start(ctx, "Move") - defer span.End() - var oldNode, newNode *node.Node - var err error - if oldNode, err = fs.lu.NodeFromResource(ctx, oldRef); err != nil { - return nil, err - } - - if !oldNode.Exists { - return nil, errtypes.NotFound(filepath.Join(oldNode.ParentID, oldNode.Name)) - } - - orp, err := fs.p.AssemblePermissions(ctx, oldNode) - switch { - case err != nil: - return nil, err - case !orp.Move: - f, _ := storagespace.FormatReference(oldRef) - if orp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - - if newNode, err = fs.lu.NodeFromResource(ctx, newRef); err != nil { - return nil, err - } - if newNode.Exists { - return nil, errtypes.AlreadyExists(filepath.Join(newNode.ParentID, newNode.Name)) - } - - nrp, err := fs.p.AssemblePermissions(ctx, newNode) - switch { - case err != nil: - return nil, err - case oldNode.IsDir(ctx) && !nrp.CreateContainer: - f, _ := storagespace.FormatReference(newRef) - if nrp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - case !oldNode.IsDir(ctx) && !nrp.InitiateFileUpload: - f, _ := storagespace.FormatReference(newRef) - if nrp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - - // check lock on source - if err := oldNode.CheckLock(ctx); err != nil { - return nil, err - } - - // check processing on source - if oldNode.IsProcessing(ctx) { - return nil, errtypes.ResourceProcessing(oldRef.String()) - } - - if err := fs.tp.Move(ctx, oldNode, newNode); err != nil { - return nil, err - } - - log := appctx.GetLogger(ctx) - newResolved := newRef - if nref, err := fs.refFromNode(ctx, newNode, newRef.GetResourceId().GetStorageId(), nrp); err != nil { - log.Error().Err(err).Msg("move: failed to resolve new reference") - } else { - newResolved = nref - } - oldResolved := oldRef - if oref, err := fs.refFromNode(ctx, oldNode, oldRef.GetResourceId().GetStorageId(), orp); err != nil { - log.Error().Err(err).Msg("move: failed to resolve old reference") - } else { - oldResolved = oref - } - return &storage.MoveResult{ - SpaceOwner: newNode.SpaceOwnerOrManager(ctx), - OldReference: oldResolved, - NewReference: newResolved, - }, nil -} - -// GetMD returns the metadata for the specified resource -func (fs *Decomposedfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) (ri *provider.ResourceInfo, err error) { - ctx, span := tracer.Start(ctx, "GetMD") - defer span.End() - var node *node.Node - if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return - } - - if !node.Exists { - err = errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - return - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return nil, err - case !rp.Stat: - f, _ := storagespace.FormatReference(ref) - return nil, errtypes.NotFound(f) - } - - md, err := node.AsResourceInfo(ctx, rp, mdKeys, fieldMask, utils.IsRelativeReference(ref)) - if err != nil { - return nil, err - } - - addSpace := len(fieldMask) == 0 - for _, p := range fieldMask { - if p == "space" || p == "*" { - addSpace = true - break - } - } - if addSpace { - if md.Space, err = fs.StorageSpaceFromNode(ctx, node, true); err != nil { - return nil, err - } - } - - return md, nil -} - -// ListFolder returns a list of resources in the specified folder -func (fs *Decomposedfs) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) ([]*provider.ResourceInfo, error) { - ctx, span := tracer.Start(ctx, "ListFolder") - defer span.End() - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return nil, err - } - - if !n.Exists { - return nil, errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !rp.ListContainer: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - - children, err := fs.tp.ListFolder(ctx, n) - if err != nil { - return nil, err - } - - numWorkers := fs.o.MaxConcurrency - if len(children) < numWorkers { - numWorkers = len(children) - } - work := make(chan *node.Node, len(children)) - results := make(chan *provider.ResourceInfo, len(children)) - - g, ctx := errgroup.WithContext(ctx) - - // Distribute work - g.Go(func() error { - defer close(work) - for _, child := range children { - select { - case work <- child: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - - // Spawn workers that'll concurrently work the queue - for i := 0; i < numWorkers; i++ { - g.Go(func() error { - for child := range work { - np := rp - // add this childs permissions - pset, _ := child.PermissionSet(ctx) - node.AddPermissions(np, pset) - ri, err := child.AsResourceInfo(ctx, np, mdKeys, fieldMask, utils.IsRelativeReference(ref)) - if err != nil { - return errtypes.InternalError(err.Error()) - } - select { - case results <- ri: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - } - - // Wait for things to settle down, then close results chan - go func() { - _ = g.Wait() // error is checked later - close(results) - }() - - finfos := make([]*provider.ResourceInfo, len(children)) - i := 0 - for fi := range results { - finfos[i] = fi - i++ - } - - if err := g.Wait(); err != nil { - return nil, err - } - - return finfos, nil -} - -// Delete deletes the specified resource -func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (err error) { - ctx, span := tracer.Start(ctx, "Delete") - defer span.End() - var node *node.Node - if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return - } - if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - } - - if node.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return err - case !rp.Delete: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, node.SpaceOwnerOrManager(ctx)) - - if err := node.CheckLock(ctx); err != nil { - return err - } - - return fs.tp.Delete(ctx, node) -} - -// Download returns a reader to the specified resource -func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { - ctx, span := tracer.Start(ctx, "Download") - defer span.End() - // check if we are trying to download a revision - // TODO the CS3 api should allow initiating a revision download - if ref.ResourceId != nil && strings.Contains(ref.ResourceId.OpaqueId, node.RevisionIDDelimiter) { - return fs.DownloadRevision(ctx, ref, ref.ResourceId.OpaqueId, openReaderFunc) - } - - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return nil, nil, err - } - - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return nil, nil, err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, nil, err - case !rp.InitiateFileDownload: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, nil, errtypes.PermissionDenied(f) - } - return nil, nil, errtypes.NotFound(f) - } - - // check processing - if n.IsProcessing(ctx) { - return nil, nil, errtypes.ResourceProcessing(ref.String()) - } - ri, err := n.AsResourceInfo(ctx, rp, nil, []string{"size", "mimetype", "etag"}, true) - if err != nil { - return nil, nil, err - } - var reader io.ReadCloser - if openReaderFunc(ri) { - reader, err = fs.tp.ReadBlob(n) - if err != nil { - return nil, nil, errors.Wrap(err, "Decomposedfs: error download blob '"+n.ID+"'") - } - } - return ri, reader, nil -} - -// GetLock returns an existing lock on the given reference -func (fs *Decomposedfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { - ctx, span := tracer.Start(ctx, "GetLock") - defer span.End() - node, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error resolving ref") - } - - if !node.Exists { - err = errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - return nil, err - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return nil, err - case !rp.InitiateFileDownload: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - - return node.ReadLock(ctx, false) -} - -// SetLock puts a lock on the given reference -func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - ctx, span := tracer.Start(ctx, "SetLock") - defer span.End() - node, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") - } - - if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - return node.SetLock(ctx, lock) -} - -// RefreshLock refreshes an existing lock on the given reference -func (fs *Decomposedfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { - ctx, span := tracer.Start(ctx, "RefreshLock") - defer span.End() - if lock.LockId == "" { - return errtypes.BadRequest("missing lockid") - } - - node, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") - } - - if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - return node.RefreshLock(ctx, lock, existingLockID) -} - -// Unlock removes an existing lock from the given reference -func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { - ctx, span := tracer.Start(ctx, "Unlock") - defer span.End() - if lock.LockId == "" { - return errtypes.BadRequest("missing lockid") - } - - node, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") - } - - if !node.Exists { - return errtypes.NotFound(filepath.Join(node.ParentID, node.Name)) - } - - rp, err := fs.p.AssemblePermissions(ctx, node) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: // TODO do we need a dedicated permission? - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - return node.Unlock(ctx, lock) -} - -func (fs *Decomposedfs) AddLabel(ctx context.Context, ref *provider.Reference, userID *user.UserId, label string) error { - return errtypes.NotSupported("AddLabel not implemented") -} - -func (fs *Decomposedfs) RemoveLabel(ctx context.Context, ref *provider.Reference, userID *user.UserId, label string) error { - return errtypes.NotSupported("RemoveLabel not implemented") -} - -func (fs *Decomposedfs) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) { - return fs.trashbin.ListRecycle(ctx, ref, key, relativePath) -} -func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { - return fs.trashbin.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef) -} -func (fs *Decomposedfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { - return fs.trashbin.PurgeRecycleItem(ctx, ref, key, relativePath) -} -func (fs *Decomposedfs) EmptyRecycle(ctx context.Context, ref *provider.Reference) error { - return fs.trashbin.EmptyRecycle(ctx, ref) -} - -func (fs *Decomposedfs) getNodePath(ctx context.Context, n *node.Node, perms *provider.ResourcePermissions) (string, error) { - hp := func(n *node.Node) bool { - return perms.GetGetPath() - } - return fs.lu.Path(ctx, n, hp) -} - -func (fs *Decomposedfs) refFromNode(ctx context.Context, n *node.Node, storageId string, perms *provider.ResourcePermissions) (*provider.Reference, error) { - var err error - if perms == nil { - perms, err = fs.p.AssemblePermissions(ctx, n) - if err != nil { - return nil, err - } - } - path, err := fs.getNodePath(ctx, n, perms) - if err != nil { - return nil, err - } - return &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: storageId, - OpaqueId: n.SpaceID, - SpaceId: n.SpaceID, - }, - Path: path, - }, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/grants.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/grants.go deleted file mode 100644 index b8f64331a4..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/grants.go +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "path/filepath" - "strings" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/ace" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -// DenyGrant denies access to a resource. -func (fs *Decomposedfs) DenyGrant(ctx context.Context, ref *provider.Reference, grantee *provider.Grantee) error { - _, span := tracer.Start(ctx, "DenyGrant") - defer span.End() - log := appctx.GetLogger(ctx) - - log.Debug().Interface("ref", ref).Interface("grantee", grantee).Msg("DenyGrant()") - - grantNode, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return err - } - if !grantNode.Exists { - return errtypes.NotFound(filepath.Join(grantNode.ParentID, grantNode.Name)) - } - - // set all permissions to false - grant := &provider.Grant{ - Grantee: grantee, - Permissions: &provider.ResourcePermissions{}, - } - - // add acting user - u := ctxpkg.ContextMustGetUser(ctx) - grant.Creator = u.GetId() - - rp, err := fs.p.AssemblePermissions(ctx, grantNode) - - switch { - case err != nil: - return err - case !rp.DenyGrant: - return errtypes.PermissionDenied(filepath.Join(grantNode.ParentID, grantNode.Name)) - } - - return fs.storeGrant(ctx, grantNode, grant) -} - -// AddGrant adds a grant to a resource -func (fs *Decomposedfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) { - _, span := tracer.Start(ctx, "AddGrant") - defer span.End() - log := appctx.GetLogger(ctx) - log.Debug().Interface("ref", ref).Interface("grant", g).Msg("AddGrant()") - grantNode, unlockFunc, grant, err := fs.loadGrant(ctx, ref, g) - if err != nil { - return err - } - defer func() { - _ = unlockFunc() - }() - - if grant != nil { - return errtypes.AlreadyExists(filepath.Join(grantNode.ParentID, grantNode.Name)) - } - - owner := grantNode.Owner() - grants, err := grantNode.ListGrants(ctx) - if err != nil { - return err - } - - // If the owner is empty and there are no grantees then we are dealing with a just created project space. - // In this case we don't need to check for permissions and just add the grant since this will be the project - // manager. - // When the owner is empty but grants are set then we do want to check the grants. - // However, if we are trying to edit an existing grant we do not have to check for permission if the user owns the grant - // TODO: find a better to check this - if len(grants) != 0 || (owner != nil && owner.OpaqueId != "" && (owner.OpaqueId != grantNode.SpaceID || owner.Type != 8)) { - rp, err := fs.p.AssemblePermissions(ctx, grantNode) - switch { - case err != nil: - return err - case !rp.AddGrant: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - } - // check processing - if grantNode.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - return fs.storeGrant(ctx, grantNode, g) -} - -// ListGrants lists the grants on the specified resource -func (fs *Decomposedfs) ListGrants(ctx context.Context, ref *provider.Reference) (grants []*provider.Grant, err error) { - _, span := tracer.Start(ctx, "ListGrants") - defer span.End() - var grantNode *node.Node - if grantNode, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return - } - if !grantNode.Exists { - err = errtypes.NotFound(filepath.Join(grantNode.ParentID, grantNode.Name)) - return - } - rp, err := fs.p.AssemblePermissions(ctx, grantNode) - switch { - case err != nil: - return nil, err - case !rp.ListGrants && !rp.Stat: - f, _ := storagespace.FormatReference(ref) - return nil, errtypes.NotFound(f) - } - log := appctx.GetLogger(ctx) - var attrs node.Attributes - if attrs, err = grantNode.Xattrs(ctx); err != nil { - log.Error().Err(err).Msg("error listing attributes") - return nil, err - } - - aces := []*ace.ACE{} - for k, v := range attrs { - if strings.HasPrefix(k, prefixes.GrantPrefix) { - var err error - var e *ace.ACE - principal := k[len(prefixes.GrantPrefix):] - if e, err = ace.Unmarshal(principal, v); err != nil { - log.Error().Err(err).Str("principal", principal).Str("attr", k).Msg("could not unmarshal ace") - continue - } - aces = append(aces, e) - } - } - - uid := ctxpkg.ContextMustGetUser(ctx).GetId() - grants = make([]*provider.Grant, 0, len(aces)) - for i := range aces { - g := aces[i].Grant() - - // you may list your own grants even without listgrants permission - if !rp.ListGrants && !utils.UserIDEqual(g.Creator, uid) && !utils.UserIDEqual(g.Grantee.GetUserId(), uid) { - continue - } - - grants = append(grants, g) - } - - return grants, nil -} - -// RemoveGrant removes a grant from resource -func (fs *Decomposedfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) { - _, span := tracer.Start(ctx, "RemoveGrant") - defer span.End() - grantNode, unlockFunc, grant, err := fs.loadGrant(ctx, ref, g) - if err != nil { - return err - } - defer func() { - _ = unlockFunc() - }() - - if grant == nil { - return errtypes.NotFound("grant not found") - } - - // you are allowed to remove grants if you created them yourself or have the proper permission - if !utils.UserIDEqual(grant.Creator, ctxpkg.ContextMustGetUser(ctx).GetId()) { - rp, err := fs.p.AssemblePermissions(ctx, grantNode) - switch { - case err != nil: - return err - case !rp.RemoveGrant: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - } - // check processing - if grantNode.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - if err := grantNode.DeleteGrant(ctx, g, false); err != nil { - return err - } - - if isShareGrant(ctx) { - // do not invalidate by user or group indexes - // FIXME we should invalidate the by-type index, but that requires reference counting - } else { - // invalidate space grant - switch g.Grantee.Type { - case provider.GranteeType_GRANTEE_TYPE_USER: - // remove from user index - if err := fs.userSpaceIndex.Remove(g.Grantee.GetUserId().GetOpaqueId(), grantNode.SpaceID); err != nil { - return err - } - case provider.GranteeType_GRANTEE_TYPE_GROUP: - // remove from group index - if err := fs.groupSpaceIndex.Remove(g.Grantee.GetGroupId().GetOpaqueId(), grantNode.SpaceID); err != nil { - return err - } - } - } - - return fs.tp.Propagate(ctx, grantNode, 0) -} - -func isShareGrant(ctx context.Context) bool { - _, ok := storageprovider.SpaceTypeFromContext(ctx) - return !ok -} - -// UpdateGrant updates a grant on a resource -// TODO remove AddGrant or UpdateGrant grant from CS3 api, redundant? tracked in https://github.com/cs3org/cs3apis/issues/92 -func (fs *Decomposedfs) UpdateGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { - _, span := tracer.Start(ctx, "UpdateGrant") - defer span.End() - log := appctx.GetLogger(ctx) - log.Debug().Interface("ref", ref).Interface("grant", g).Msg("UpdateGrant()") - - grantNode, unlockFunc, grant, err := fs.loadGrant(ctx, ref, g) - if err != nil { - return err - } - defer func() { - _ = unlockFunc() - }() - - if grant == nil { - // grant not found - // TODO: fallback to AddGrant? - return errtypes.NotFound(g.Grantee.GetUserId().GetOpaqueId()) - } - - // You may update a grant when you have the UpdateGrant permission or created the grant (regardless what your permissions are now) - if !utils.UserIDEqual(grant.Creator, ctxpkg.ContextMustGetUser(ctx).GetId()) { - rp, err := fs.p.AssemblePermissions(ctx, grantNode) - switch { - case err != nil: - return err - case !rp.UpdateGrant: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - } - - // check processing - if grantNode.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - return fs.storeGrant(ctx, grantNode, g) -} - -// checks if the given grant exists and returns it. Nil grant means it doesn't exist -func (fs *Decomposedfs) loadGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (*node.Node, metadata.UnlockFunc, *provider.Grant, error) { - _, span := tracer.Start(ctx, "loadGrant") - defer span.End() - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return nil, nil, nil, err - } - if !n.Exists { - return nil, nil, nil, errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - } - - // lock the metadata file - unlockFunc, err := fs.lu.MetadataBackend().Lock(n.InternalPath()) - if err != nil { - return nil, nil, nil, err - } - - grants, err := n.ListGrants(ctx) - if err != nil { - return nil, nil, nil, err - } - - for _, grant := range grants { - switch grant.Grantee.GetType() { - case provider.GranteeType_GRANTEE_TYPE_USER: - if g.Grantee.GetUserId().GetOpaqueId() == grant.Grantee.GetUserId().GetOpaqueId() { - return n, unlockFunc, grant, nil - } - case provider.GranteeType_GRANTEE_TYPE_GROUP: - if g.Grantee.GetGroupId().GetOpaqueId() == grant.Grantee.GetGroupId().GetOpaqueId() { - return n, unlockFunc, grant, nil - } - } - } - - return n, unlockFunc, nil, nil -} - -func (fs *Decomposedfs) storeGrant(ctx context.Context, n *node.Node, g *provider.Grant) error { - _, span := tracer.Start(ctx, "storeGrant") - defer span.End() - // if is a grant to a space root, the receiver needs the space type to update the indexes - spaceType, ok := storageprovider.SpaceTypeFromContext(ctx) - if !ok { - // this is not a grant on a space root we are just adding a share - spaceType = spaceTypeShare - } - - // set the grant - e := ace.FromGrant(g) - principal, value := e.Marshal() - attribs := node.Attributes{ - prefixes.GrantPrefix + principal: value, - } - if err := n.SetXattrsWithContext(ctx, attribs, false); err != nil { - appctx.GetLogger(ctx).Error().Err(err). - Str("principal", principal).Msg("Could not set grant for principal") - return err - } - - // update the indexes only after successfully setting the grant - err := fs.updateIndexes(ctx, g.GetGrantee(), spaceType, n.SpaceID, n.ID) - if err != nil { - return err - } - - return fs.tp.Propagate(ctx, n, 0) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup/lookup.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup/lookup.go deleted file mode 100644 index 70d11d4848..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup/lookup.go +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package lookup - -import ( - "context" - "fmt" - "os" - "path/filepath" - "strings" - - user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" -) - -var tracer trace.Tracer - -const ( - _spaceTypePersonal = "personal" -) - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/lookup") -} - -// Lookup implements transformations from filepath to node and back -type Lookup struct { - Options *options.Options - - metadataBackend metadata.Backend - tm node.TimeManager -} - -// New returns a new Lookup instance -func New(b metadata.Backend, o *options.Options, tm node.TimeManager) *Lookup { - return &Lookup{ - Options: o, - metadataBackend: b, - tm: tm, - } -} - -// MetadataBackend returns the metadata backend -func (lu *Lookup) MetadataBackend() metadata.Backend { - return lu.metadataBackend -} - -func (lu *Lookup) ReadBlobIDAndSizeAttr(ctx context.Context, path string, attrs node.Attributes) (string, int64, error) { - blobID := "" - blobSize := int64(0) - var err error - - if attrs != nil { - blobID = attrs.String(prefixes.BlobIDAttr) - if blobID != "" { - blobSize, err = attrs.Int64(prefixes.BlobsizeAttr) - if err != nil { - return "", 0, err - } - } - } else { - attrs, err := lu.metadataBackend.All(ctx, path) - if err != nil { - return "", 0, errors.Wrapf(err, "error reading blobid xattr") - } - nodeAttrs := node.Attributes(attrs) - blobID = nodeAttrs.String(prefixes.BlobIDAttr) - blobSize, err = nodeAttrs.Int64(prefixes.BlobsizeAttr) - if err != nil { - return "", 0, errors.Wrapf(err, "error reading blobsize xattr") - } - } - return blobID, blobSize, nil -} - -func readChildNodeFromLink(path string) (string, error) { - link, err := os.Readlink(path) - if err != nil { - return "", err - } - nodeID := strings.TrimLeft(link, "/.") - nodeID = strings.ReplaceAll(nodeID, "/", "") - return nodeID, nil -} - -func (lu *Lookup) NodeIDFromParentAndName(ctx context.Context, parent *node.Node, name string) (string, error) { - nodeID, err := readChildNodeFromLink(filepath.Join(parent.InternalPath(), name)) - if err != nil { - return "", errors.Wrap(err, "decomposedfs: Wrap: readlink error") - } - return nodeID, nil -} - -// TypeFromPath returns the type of the node at the given path -func (lu *Lookup) TypeFromPath(ctx context.Context, path string) provider.ResourceType { - // Try to read from xattrs - typeAttr, err := lu.metadataBackend.GetInt64(ctx, path, prefixes.TypeAttr) - if err == nil { - return provider.ResourceType(int32(typeAttr)) - } - - t := provider.ResourceType_RESOURCE_TYPE_INVALID - // Fall back to checking on disk - fi, err := os.Lstat(path) - if err != nil { - return t - } - - switch { - case fi.IsDir(): - if _, err = lu.metadataBackend.Get(ctx, path, prefixes.ReferenceAttr); err == nil { - t = provider.ResourceType_RESOURCE_TYPE_REFERENCE - } else { - t = provider.ResourceType_RESOURCE_TYPE_CONTAINER - } - case fi.Mode().IsRegular(): - t = provider.ResourceType_RESOURCE_TYPE_FILE - case fi.Mode()&os.ModeSymlink != 0: - t = provider.ResourceType_RESOURCE_TYPE_SYMLINK - // TODO reference using ext attr on a symlink - // nodeType = provider.ResourceType_RESOURCE_TYPE_REFERENCE - } - return t -} - -// NodeFromResource takes in a request path or request id and converts it to a Node -func (lu *Lookup) NodeFromResource(ctx context.Context, ref *provider.Reference) (*node.Node, error) { - ctx, span := tracer.Start(ctx, "NodeFromResource") - defer span.End() - - if ref.ResourceId != nil { - // check if a storage space reference is used - // currently, the decomposed fs uses the root node id as the space id - n, err := lu.NodeFromID(ctx, ref.ResourceId) - if err != nil { - return nil, err - } - // is this a relative reference? - if ref.Path != "" { - p := filepath.Clean(ref.Path) - if p != "." && p != "/" { - // walk the relative path - n, err = lu.WalkPath(ctx, n, p, false, func(ctx context.Context, n *node.Node) error { return nil }) - if err != nil { - return nil, err - } - n.SpaceID = ref.ResourceId.SpaceId - } - } - return n, nil - } - - // reference is invalid - return nil, fmt.Errorf("invalid reference %+v. resource_id must be set", ref) -} - -// NodeFromID returns the internal path for the id -func (lu *Lookup) NodeFromID(ctx context.Context, id *provider.ResourceId) (n *node.Node, err error) { - ctx, span := tracer.Start(ctx, "NodeFromID") - defer span.End() - if id == nil { - return nil, fmt.Errorf("invalid resource id %+v", id) - } - if id.OpaqueId == "" { - // The Resource references the root of a space - return lu.NodeFromSpaceID(ctx, id.SpaceId) - } - return node.ReadNode(ctx, lu, id.SpaceId, id.OpaqueId, false, nil, false) -} - -// Pathify segments the beginning of a string into depth segments of width length -// Pathify("aabbccdd", 3, 1) will return "a/a/b/bccdd" -func Pathify(id string, depth, width int) string { - b := strings.Builder{} - i := 0 - for ; i < depth; i++ { - if len(id) <= i*width+width { - break - } - b.WriteString(id[i*width : i*width+width]) - b.WriteRune(filepath.Separator) - } - b.WriteString(id[i*width:]) - return b.String() -} - -// NodeFromSpaceID converts a resource id into a Node -func (lu *Lookup) NodeFromSpaceID(ctx context.Context, spaceID string) (n *node.Node, err error) { - node, err := node.ReadNode(ctx, lu, spaceID, spaceID, false, nil, false) - if err != nil { - return nil, err - } - - node.SpaceRoot = node - return node, nil -} - -// GenerateSpaceID generates a new space id and alias -func (lu *Lookup) GenerateSpaceID(spaceType string, owner *user.User) (string, error) { - switch spaceType { - case _spaceTypePersonal: - return owner.Id.OpaqueId, nil - default: - return uuid.New().String(), nil - } -} - -// Path returns the path for node -func (lu *Lookup) Path(ctx context.Context, n *node.Node, hasPermission node.PermissionFunc) (p string, err error) { - root := n.SpaceRoot - var child *node.Node - for n.ID != root.ID { - p = filepath.Join(n.Name, p) - child = n - if n, err = n.Parent(ctx); err != nil { - appctx.GetLogger(ctx). - Error().Err(err). - Str("path", p). - Str("spaceid", child.SpaceID). - Str("nodeid", child.ID). - Str("parentid", child.ParentID). - Msg("Path()") - return - } - - if !hasPermission(n) { - break - } - } - p = filepath.Join("/", p) - return -} - -// WalkPath calls n.Child(segment) on every path segment in p starting at the node r. -// If a function f is given it will be executed for every segment node, but not the root node r. -// If followReferences is given the current visited reference node is replaced by the referenced node. -func (lu *Lookup) WalkPath(ctx context.Context, r *node.Node, p string, followReferences bool, f func(ctx context.Context, n *node.Node) error) (*node.Node, error) { - segments := strings.Split(strings.Trim(p, "/"), "/") - var err error - for i := range segments { - if r, err = r.Child(ctx, segments[i]); err != nil { - return r, err - } - - if followReferences { - if attrBytes, err := r.Xattr(ctx, prefixes.ReferenceAttr); err == nil { - realNodeID := attrBytes - ref, err := refFromCS3(realNodeID) - if err != nil { - return nil, err - } - - r, err = lu.NodeFromID(ctx, ref.ResourceId) - if err != nil { - return nil, err - } - } - } - if r.IsSpaceRoot(ctx) { - r.SpaceRoot = r - } - - if !r.Exists && i < len(segments)-1 { - return r, errtypes.NotFound(segments[i]) - } - if f != nil { - if err = f(ctx, r); err != nil { - return r, err - } - } - } - return r, nil -} - -// InternalRoot returns the internal storage root directory -func (lu *Lookup) InternalRoot() string { - return lu.Options.Root -} - -// InternalPath returns the internal path for a given ID -func (lu *Lookup) InternalPath(spaceID, nodeID string) string { - return filepath.Join(lu.Options.Root, "spaces", Pathify(spaceID, 1, 2), "nodes", Pathify(nodeID, 4, 2)) -} - -// // ReferenceFromAttr returns a CS3 reference from xattr of a node. -// // Supported formats are: "cs3:storageid/nodeid" -// func ReferenceFromAttr(b []byte) (*provider.Reference, error) { -// return refFromCS3(b) -// } - -// refFromCS3 creates a CS3 reference from a set of bytes. This method should remain private -// and only be called after validation because it can potentially panic. -func refFromCS3(b []byte) (*provider.Reference, error) { - parts := string(b[4:]) - return &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: strings.Split(parts, "/")[0], - OpaqueId: strings.Split(parts, "/")[1], - }, - }, nil -} - -// CopyMetadata copies all extended attributes from source to target. -// The optional filter function can be used to filter by attribute name, e.g. by checking a prefix -// For the source file, a shared lock is acquired. -// NOTE: target resource will be write locked! -func (lu *Lookup) CopyMetadata(ctx context.Context, src, target string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), acquireTargetLock bool) (err error) { - // Acquire a read log on the source node - // write lock existing node before reading treesize or tree time - lock, err := lockedfile.OpenFile(lu.MetadataBackend().LockfilePath(src), os.O_RDONLY|os.O_CREATE, 0600) - if err != nil { - return err - } - - if err != nil { - return errors.Wrap(err, "xattrs: Unable to lock source to read") - } - defer func() { - rerr := lock.Close() - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - return lu.CopyMetadataWithSourceLock(ctx, src, target, filter, lock, acquireTargetLock) -} - -// CopyMetadataWithSourceLock copies all extended attributes from source to target. -// The optional filter function can be used to filter by attribute name, e.g. by checking a prefix -// For the source file, a matching lockedfile is required. -// NOTE: target resource will be write locked! -func (lu *Lookup) CopyMetadataWithSourceLock(ctx context.Context, sourcePath, targetPath string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), lockedSource *lockedfile.File, acquireTargetLock bool) (err error) { - switch { - case lockedSource == nil: - return errors.New("no lock provided") - case lockedSource.Name() != lu.MetadataBackend().LockfilePath(sourcePath): - return errors.New("lockpath does not match filepath") - } - - attrs, err := lu.metadataBackend.All(ctx, sourcePath) - if err != nil { - return err - } - - newAttrs := make(map[string][]byte, 0) - for attrName, val := range attrs { - if filter != nil { - var ok bool - if val, ok = filter(attrName, val); !ok { - continue - } - } - newAttrs[attrName] = val - } - - return lu.MetadataBackend().SetMultiple(ctx, targetPath, newAttrs, acquireTargetLock) -} - -// TimeManager returns the time manager -func (lu *Lookup) TimeManager() node.TimeManager { - return lu.tm -} - -// DetectBackendOnDisk returns the name of the metadata backend being used on disk -func DetectBackendOnDisk(root string) string { - matches, _ := filepath.Glob(filepath.Join(root, "spaces", "*", "*")) - if len(matches) > 0 { - base := matches[len(matches)-1] - spaceid := strings.ReplaceAll( - strings.TrimPrefix(base, filepath.Join(root, "spaces")), - "/", "") - spaceRoot := Pathify(spaceid, 4, 2) - _, err := os.Stat(filepath.Join(base, "nodes", spaceRoot+".mpk")) - if err == nil { - return "mpk" - } - _, err = os.Stat(filepath.Join(base, "nodes", spaceRoot+".ini")) - if err == nil { - return "ini" - } - } - return "xattrs" -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata.go deleted file mode 100644 index becd43b87e..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "fmt" - "path/filepath" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" -) - -// SetArbitraryMetadata sets the metadata on a resource -func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) (err error) { - _, span := tracer.Start(ctx, "SetArbitraryMetadata") - defer span.End() - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") - } - sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() - - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: // TODO add explicit SetArbitraryMetadata grant to CS3 api, tracked in https://github.com/cs3org/cs3apis/issues/91 - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - // check lock - if err := n.CheckLock(ctx); err != nil { - return err - } - - errs := []error{} - // TODO should we really continue updating when an error occurs? - if md.Metadata != nil { - if val, ok := md.Metadata["mtime"]; ok { - delete(md.Metadata, "mtime") - if err := n.SetMtimeString(ctx, val); err != nil { - errs = append(errs, errors.Wrap(err, "could not set mtime")) - } - } - // TODO(jfd) special handling for atime? - // TODO(jfd) allow setting birth time (btime)? - // TODO(jfd) any other metadata that is interesting? fileid? - // TODO unset when file is updated - // TODO unset when folder is updated or add timestamp to etag? - if val, ok := md.Metadata["etag"]; ok { - delete(md.Metadata, "etag") - if err := n.SetEtag(ctx, val); err != nil { - errs = append(errs, errors.Wrap(err, "could not set etag")) - } - } - if val, ok := md.Metadata[node.FavoriteKey]; ok { - delete(md.Metadata, node.FavoriteKey) - if u, ok := ctxpkg.ContextGetUser(ctx); ok { - if uid := u.GetId(); uid != nil { - if err := n.SetFavorite(ctx, uid, val); err != nil { - sublog.Error().Err(err). - Interface("user", u). - Msg("could not set favorite flag") - errs = append(errs, errors.Wrap(err, "could not set favorite flag")) - } - } else { - sublog.Error().Interface("user", u).Msg("user has no id") - errs = append(errs, errors.Wrap(errtypes.UserRequired("userrequired"), "user has no id")) - } - } else { - sublog.Error().Interface("user", u).Msg("error getting user from ctx") - errs = append(errs, errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx")) - } - } - } - for k, v := range md.Metadata { - attrName := prefixes.MetadataPrefix + k - if err = n.SetXattrString(ctx, attrName, v); err != nil { - errs = append(errs, errors.Wrap(err, "Decomposedfs: could not set metadata attribute "+attrName+" to "+k)) - } - } - - switch len(errs) { - case 0: - return fs.tp.Propagate(ctx, n, 0) - case 1: - // TODO Propagate if anything changed - return errs[0] - default: - // TODO Propagate if anything changed - // TODO how to return multiple errors? - return errors.New("multiple errors occurred, see log for details") - } -} - -// UnsetArbitraryMetadata unsets the metadata on the given resource -func (fs *Decomposedfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) (err error) { - _, span := tracer.Start(ctx, "UnsetArbitraryMetadata") - defer span.End() - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") - } - sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() - - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return err - case !rp.InitiateFileUpload: // TODO use SetArbitraryMetadata grant to CS3 api, tracked in https://github.com/cs3org/cs3apis/issues/91 - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - // check lock - if err := n.CheckLock(ctx); err != nil { - return err - } - - errs := []error{} - for _, k := range keys { - switch k { - case node.FavoriteKey: - // the favorite flag is specific to the user, so we need to incorporate the userid - u, ok := ctxpkg.ContextGetUser(ctx) - if !ok { - sublog.Error(). - Interface("user", u). - Msg("error getting user from ctx") - errs = append(errs, errors.Wrap(errtypes.UserRequired("userrequired"), "error getting user from ctx")) - continue - } - var uid *userpb.UserId - if uid = u.GetId(); uid == nil || uid.OpaqueId == "" { - sublog.Error(). - Interface("user", u). - Msg("user has no id") - errs = append(errs, errors.Wrap(errtypes.UserRequired("userrequired"), "user has no id")) - continue - } - fa := fmt.Sprintf("%s:%s:%s@%s", prefixes.FavPrefix, utils.UserTypeToString(uid.GetType()), uid.GetOpaqueId(), uid.GetIdp()) - if err := n.RemoveXattr(ctx, fa, true); err != nil { - if metadata.IsAttrUnset(err) { - continue // already gone, ignore - } - sublog.Error().Err(err). - Interface("user", u). - Str("key", fa). - Msg("could not unset favorite flag") - errs = append(errs, errors.Wrap(err, "could not unset favorite flag")) - } - default: - if err = n.RemoveXattr(ctx, prefixes.MetadataPrefix+k, true); err != nil { - if metadata.IsAttrUnset(err) { - continue // already gone, ignore - } - sublog.Error().Err(err). - Str("key", k). - Msg("could not unset metadata") - errs = append(errs, errors.Wrap(err, "could not unset metadata")) - } - } - } - switch len(errs) { - case 0: - return fs.tp.Propagate(ctx, n, 0) - case 1: - // TODO Propagate if anything changed - return errs[0] - default: - // TODO Propagate if anything changed - // TODO how to return multiple errors? - return errors.New("multiple errors occurred, see log for details") - } -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/errors.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/errors.go deleted file mode 100644 index 6d2f4f6d9c..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/errors.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package metadata - -import ( - "io/fs" - "os" - "syscall" - - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/pkg/errors" - "github.com/pkg/xattr" -) - -// IsNotExist checks if there is a os not exists error buried inside the xattr error, -// as we cannot just use os.IsNotExist(). -func IsNotExist(err error) bool { - if _, ok := err.(errtypes.IsNotFound); ok { - return true - } - if os.IsNotExist(errors.Cause(err)) { - return true - } - if xerr, ok := errors.Cause(err).(*xattr.Error); ok { - if serr, ok2 := xerr.Err.(syscall.Errno); ok2 { - return serr == syscall.ENOENT - } - } - return false -} - -// IsErrRange checks for a syscall.ERANGE buried inside an xattr error. listxattr -// returns ERANGE when the set of attribute names grows between the size-probe call -// and the read call (a concurrent setxattr landed in between). This is transient and -// self-clearing once the competing writer finishes its batch. -func IsErrRange(err error) bool { - if xerr, ok := errors.Cause(err).(*xattr.Error); ok { - if serr, ok2 := xerr.Err.(syscall.Errno); ok2 { - return serr == syscall.ERANGE - } - } - return false -} - -// IsErrTooBig checks for a syscall.E2BIG buried inside an xattr error. listxattr -// returns E2BIG when the attribute name list is larger than the maximum size the -// kernel will hand out (the 64KiB VFS limit, e.g. on XFS). Unlike ERANGE this is -// not a transient race: the list cannot be retrieved at all, so callers should -// fail fast instead of retrying. -func IsErrTooBig(err error) bool { - if xerr, ok := errors.Cause(err).(*xattr.Error); ok { - if serr, ok2 := xerr.Err.(syscall.Errno); ok2 { - return serr == syscall.E2BIG - } - } - return false -} - -// IsAttrUnset checks the xattr.ENOATTR from the xattr package which redifines it as ENODATA on platforms that do not natively support it (eg. linux) -// see https://github.com/pkg/xattr/blob/8725d4ccc0fcef59c8d9f0eaf606b3c6f962467a/xattr_linux.go#L19-L22 -func IsAttrUnset(err error) bool { - if xerr, ok := errors.Cause(err).(*xattr.Error); ok { - if serr, ok2 := xerr.Err.(syscall.Errno); ok2 { - return serr == xattr.ENOATTR - } - } - return false -} - -// The os error is buried inside the fs.PathError error -func IsNotDir(err error) bool { - if perr, ok := errors.Cause(err).(*fs.PathError); ok { - if serr, ok2 := perr.Err.(syscall.Errno); ok2 { - return serr == syscall.ENOTDIR - } - } - if xerr, ok := errors.Cause(err).(*xattr.Error); ok { - if serr, ok2 := xerr.Err.(syscall.Errno); ok2 { - return serr == syscall.ENOTDIR - } - } - return false -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/list.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/list.go deleted file mode 100644 index 77be5d08d0..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/list.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2026 OpenCloud GmbH -// SPDX-License-Identifier: Apache-2.0 - -package metadata - -import ( - "context" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/pkg/xattr" -) - -// maxListXattrRetries bounds the number of attempts made by listXattr when it -// keeps racing with a concurrent writer. -const maxListXattrRetries = 10 - -// listXattr lists the extended attribute names of the file at path, retrying on -// transient ERANGE errors. -// -// xattr.List is not atomic: internally it issues a listxattr syscall to learn -// the size of the extended-attribute name list, allocates a buffer of that -// size and issues a second listxattr to read the names into it. If another -// goroutine or process adds an extended attribute to the same inode between the -// two syscalls, the name list grows beyond the buffer and the kernel returns -// ERANGE ("numerical result out of range"). -// -// This is a transient condition: a fresh size query on the next attempt -// reflects the new size, so we simply retry a bounded number of times. See the -// posix fs watcher, whose assimilation can read a node's xattrs while the node -// is still being created, for a concrete source of such concurrent writes. -// -// E2BIG is deliberately not retried: it means the name list is larger than the -// maximum size the kernel will hand out (the 64KiB VFS limit, e.g. on XFS), -// which is not a race and cannot be retried away. It is returned as-is. -func listXattr(ctx context.Context, path string) ([]string, error) { - var ( - attrs []string - err error - ) - for i := 0; i < maxListXattrRetries; i++ { - attrs, err = xattr.List(path) - if err == nil { - if i > 0 { - appctx.GetLogger(ctx).Debug().Str("path", path).Int("attempt", i+1).Msg("xattr.List ERANGE recovered after retry") - } - return attrs, nil - } - if !IsErrRange(err) { - return attrs, err - } - appctx.GetLogger(ctx).Debug().Err(err).Str("path", path).Int("attempt", i+1).Msg("xattr.List ERANGE, retrying") - } - appctx.GetLogger(ctx).Error().Err(err).Str("path", path).Msg("xattr.List still failing after ERANGE retries") - return attrs, err -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/messagepack_backend.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/messagepack_backend.go deleted file mode 100644 index 4a38300965..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/messagepack_backend.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package metadata - -import ( - "context" - "errors" - "io" - "io/fs" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/google/renameio/v2" - "github.com/opencloud-eu/reva/v2/pkg/storage/cache" - "github.com/pkg/xattr" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/shamaton/msgpack/v2" - "go.opentelemetry.io/otel/codes" -) - -// MessagePackBackend persists the attributes in messagepack format inside the file -type MessagePackBackend struct { - rootPath string - metaCache cache.FileMetadataCache -} - -type readWriteCloseSeekTruncater interface { - io.ReadWriteCloser - io.Seeker - Truncate(int64) error -} - -// NewMessagePackBackend returns a new MessagePackBackend instance -func NewMessagePackBackend(rootPath string, o cache.Config) MessagePackBackend { - return MessagePackBackend{ - rootPath: filepath.Clean(rootPath), - metaCache: cache.GetFileMetadataCache(o), - } -} - -// Name returns the name of the backend -func (MessagePackBackend) Name() string { return "messagepack" } - -// All reads all extended attributes for a node -func (b MessagePackBackend) All(ctx context.Context, path string) (map[string][]byte, error) { - return b.loadAttributes(ctx, path, nil) -} - -// Get an extended attribute value for the given key -func (b MessagePackBackend) Get(ctx context.Context, path, key string) ([]byte, error) { - attribs, err := b.loadAttributes(ctx, path, nil) - if err != nil { - return []byte{}, err - } - val, ok := attribs[key] - if !ok { - return []byte{}, &xattr.Error{Op: "mpk.get", Path: path, Name: key, Err: xattr.ENOATTR} - } - return val, nil -} - -// GetInt64 reads a string as int64 from the xattrs -func (b MessagePackBackend) GetInt64(ctx context.Context, path, key string) (int64, error) { - attribs, err := b.loadAttributes(ctx, path, nil) - if err != nil { - return 0, err - } - val, ok := attribs[key] - if !ok { - return 0, &xattr.Error{Op: "mpk.get", Path: path, Name: key, Err: xattr.ENOATTR} - } - i, err := strconv.ParseInt(string(val), 10, 64) - if err != nil { - return 0, err - } - return i, nil -} - -// List retrieves a list of names of extended attributes associated with the -// given path in the file system. -func (b MessagePackBackend) List(ctx context.Context, path string) ([]string, error) { - attribs, err := b.loadAttributes(ctx, path, nil) - if err != nil { - return nil, err - } - keys := []string{} - for k := range attribs { - keys = append(keys, k) - } - return keys, nil -} - -// Set sets one attribute for the given path -func (b MessagePackBackend) Set(ctx context.Context, path, key string, val []byte) error { - return b.SetMultiple(ctx, path, map[string][]byte{key: val}, true) -} - -// SetMultiple sets a set of attribute for the given path -func (b MessagePackBackend) SetMultiple(ctx context.Context, path string, attribs map[string][]byte, acquireLock bool) error { - return b.saveAttributes(ctx, path, attribs, nil, acquireLock) -} - -// Remove an extended attribute key -func (b MessagePackBackend) Remove(ctx context.Context, path, key string, acquireLock bool) error { - return b.saveAttributes(ctx, path, nil, []string{key}, acquireLock) -} - -// AllWithLockedSource reads all extended attributes from the given reader (if possible). -// The path argument is used for storing the data in the cache -func (b MessagePackBackend) AllWithLockedSource(ctx context.Context, path string, source io.Reader) (map[string][]byte, error) { - return b.loadAttributes(ctx, path, source) -} - -func (b MessagePackBackend) saveAttributes(ctx context.Context, path string, setAttribs map[string][]byte, deleteAttribs []string, acquireLock bool) error { - var ( - err error - f readWriteCloseSeekTruncater - ) - ctx, span := tracer.Start(ctx, "saveAttributes") - defer func() { - if err != nil { - span.SetStatus(codes.Error, err.Error()) - } else { - span.SetStatus(codes.Ok, "") - } - span.End() - }() - - lockPath := b.LockfilePath(path) - metaPath := b.MetadataPath(path) - if acquireLock { - _, subspan := tracer.Start(ctx, "lockedfile.OpenFile") - f, err = lockedfile.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0600) - subspan.End() - if err != nil { - return err - } - defer f.Close() - } - // Read current state - _, subspan := tracer.Start(ctx, "os.ReadFile") - var msgBytes []byte - msgBytes, err = os.ReadFile(metaPath) - subspan.End() - attribs := map[string][]byte{} - switch { - case err != nil: - if !errors.Is(err, fs.ErrNotExist) { - return err - } - case len(msgBytes) == 0: - // ugh. an empty file? bail out - return errors.New("encountered empty metadata file") - default: - // only unmarshal if we read data - err = msgpack.Unmarshal(msgBytes, &attribs) - if err != nil { - return err - } - } - - // prepare metadata - for key, val := range setAttribs { - attribs[key] = val - } - for _, key := range deleteAttribs { - delete(attribs, key) - } - var d []byte - d, err = msgpack.Marshal(attribs) - if err != nil { - return err - } - - // overwrite file atomically - _, subspan = tracer.Start(ctx, "renameio.Writefile") - err = renameio.WriteFile(metaPath, d, 0600) - if err != nil { - return err - } - subspan.End() - - _, subspan = tracer.Start(ctx, "metaCache.PushToCache") - err = b.metaCache.PushToCache(b.cacheKey(path), attribs) - subspan.End() - return err -} - -func (b MessagePackBackend) loadAttributes(ctx context.Context, path string, source io.Reader) (map[string][]byte, error) { - ctx, span := tracer.Start(ctx, "loadAttributes") - defer span.End() - attribs := map[string][]byte{} - err := b.metaCache.PullFromCache(b.cacheKey(path), &attribs) - if err == nil { - return attribs, err - } - - metaPath := b.MetadataPath(path) - var msgBytes []byte - - if source == nil { - // // No cached entry found. Read from storage and store in cache - _, subspan := tracer.Start(ctx, "os.OpenFile") - // source, err = lockedfile.Open(metaPath) - source, err = os.Open(metaPath) - subspan.End() - // // No cached entry found. Read from storage and store in cache - if err != nil { - if os.IsNotExist(err) { - // some of the caller rely on ENOTEXISTS to be returned when the - // actual file (not the metafile) does not exist in order to - // determine whether a node exists or not -> stat the actual node - _, subspan := tracer.Start(ctx, "os.Stat") - _, err := os.Stat(path) - subspan.End() - if err != nil { - return nil, err - } - return attribs, nil // no attributes set yet - } - } - _, subspan = tracer.Start(ctx, "io.ReadAll") - msgBytes, err = io.ReadAll(source) - source.(*os.File).Close() - subspan.End() - } else { - _, subspan := tracer.Start(ctx, "io.ReadAll") - msgBytes, err = io.ReadAll(source) - subspan.End() - } - - if err != nil { - return nil, err - } - if len(msgBytes) == 0 { - return nil, errors.New("encountered empty metadata file") - } - - err = msgpack.Unmarshal(msgBytes, &attribs) - if err != nil { - return nil, err - } - - _, subspan := tracer.Start(ctx, "metaCache.PushToCache") - err = b.metaCache.PushToCache(b.cacheKey(path), attribs) - subspan.End() - if err != nil { - return nil, err - } - - return attribs, nil -} - -// IsMetaFile returns whether the given path represents a meta file -func (MessagePackBackend) IsMetaFile(path string) bool { - return strings.HasSuffix(path, ".mpk") || strings.HasSuffix(path, ".mlock") -} - -// Purge purges the data of a given path -func (b MessagePackBackend) Purge(_ context.Context, path string) error { - if err := b.metaCache.RemoveMetadata(b.cacheKey(path)); err != nil { - return err - } - return os.Remove(b.MetadataPath(path)) -} - -// Rename moves the data for a given path to a new path -func (b MessagePackBackend) Rename(oldPath, newPath string) error { - data := map[string][]byte{} - err := b.metaCache.PullFromCache(b.cacheKey(oldPath), &data) - if err == nil { - err = b.metaCache.PushToCache(b.cacheKey(newPath), data) - if err != nil { - return err - } - } - err = b.metaCache.RemoveMetadata(b.cacheKey(oldPath)) - if err != nil { - return err - } - - return os.Rename(b.MetadataPath(oldPath), b.MetadataPath(newPath)) -} - -// MetadataPath returns the path of the file holding the metadata for the given path -func (MessagePackBackend) MetadataPath(path string) string { return path + ".mpk" } - -// LockfilePath returns the path of the lock file -func (MessagePackBackend) LockfilePath(path string) string { return path + ".mlock" } - -// Lock locks the metadata for the given path -func (b MessagePackBackend) Lock(path string) (UnlockFunc, error) { - metaLockPath := b.LockfilePath(path) - mlock, err := lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return nil, err - } - return func() error { - err := mlock.Close() - if err != nil { - return err - } - return os.Remove(metaLockPath) - }, nil -} - -func (b MessagePackBackend) cacheKey(path string) string { - // rootPath is guaranteed to have no trailing slash - // the cache key shouldn't begin with a slash as some stores drop it which can cause - // confusion - return strings.TrimPrefix(path, b.rootPath+"/") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/metadata.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/metadata.go deleted file mode 100644 index 3c95586b22..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/metadata.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package metadata - -import ( - "context" - "errors" - "io" - - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" -) - -var tracer trace.Tracer - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/metadata") -} - -var errUnconfiguredError = errors.New("no metadata backend configured. Bailing out") - -type UnlockFunc func() error - -// Backend defines the interface for file attribute backends -type Backend interface { - Name() string - - All(ctx context.Context, path string) (map[string][]byte, error) - Get(ctx context.Context, path, key string) ([]byte, error) - - GetInt64(ctx context.Context, path, key string) (int64, error) - List(ctx context.Context, path string) (attribs []string, err error) - Set(ctx context.Context, path, key string, val []byte) error - SetMultiple(ctx context.Context, path string, attribs map[string][]byte, acquireLock bool) error - Remove(ctx context.Context, path, key string, acquireLock bool) error - - Lock(path string) (UnlockFunc, error) - Purge(ctx context.Context, path string) error - Rename(oldPath, newPath string) error - IsMetaFile(path string) bool - MetadataPath(path string) string - LockfilePath(path string) string - - AllWithLockedSource(ctx context.Context, path string, source io.Reader) (map[string][]byte, error) -} - -// NullBackend is the default stub backend, used to enforce the configuration of a proper backend -type NullBackend struct{} - -// Name returns the name of the backend -func (NullBackend) Name() string { return "null" } - -// All reads all extended attributes for a node -func (NullBackend) All(ctx context.Context, path string) (map[string][]byte, error) { - return nil, errUnconfiguredError -} - -// Get an extended attribute value for the given key -func (NullBackend) Get(ctx context.Context, path, key string) ([]byte, error) { - return []byte{}, errUnconfiguredError -} - -// GetInt64 reads a string as int64 from the xattrs -func (NullBackend) GetInt64(ctx context.Context, path, key string) (int64, error) { - return 0, errUnconfiguredError -} - -// List retrieves a list of names of extended attributes associated with the -// given path in the file system. -func (NullBackend) List(ctx context.Context, path string) ([]string, error) { - return nil, errUnconfiguredError -} - -// Set sets one attribute for the given path -func (NullBackend) Set(ctx context.Context, path string, key string, val []byte) error { - return errUnconfiguredError -} - -// SetMultiple sets a set of attribute for the given path -func (NullBackend) SetMultiple(ctx context.Context, path string, attribs map[string][]byte, acquireLock bool) error { - return errUnconfiguredError -} - -// Remove removes an extended attribute key -func (NullBackend) Remove(ctx context.Context, path string, key string, acquireLock bool) error { - return errUnconfiguredError -} - -// Lock locks the metadata for the given path -func (NullBackend) Lock(path string) (UnlockFunc, error) { - return nil, nil -} - -// IsMetaFile returns whether the given path represents a meta file -func (NullBackend) IsMetaFile(path string) bool { return false } - -// Purge purges the data of a given path from any cache that might hold it -func (NullBackend) Purge(_ context.Context, purges string) error { return errUnconfiguredError } - -// Rename moves the data for a given path to a new path -func (NullBackend) Rename(oldPath, newPath string) error { return errUnconfiguredError } - -// MetadataPath returns the path of the file holding the metadata for the given path -func (NullBackend) MetadataPath(path string) string { return "" } - -// LockfilePath returns the path of the lock file -func (NullBackend) LockfilePath(path string) string { return "" } - -// AllWithLockedSource reads all extended attributes from the given reader -// The path argument is used for storing the data in the cache -func (NullBackend) AllWithLockedSource(ctx context.Context, path string, source io.Reader) (map[string][]byte, error) { - return nil, errUnconfiguredError -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix.go deleted file mode 100644 index 18e94cf46c..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -//go:build !freebsd - -package prefixes - -// The default namespace for ocis. As non root users can only manipulate -// the user. namespace, which is what is used to store ownCloud specific -// metadata. To prevent name collisions with other apps, we are going to -// introduce a sub namespace "user.ocis." -const ( - OcisPrefix string = "user.ocis." -) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix_freebsd.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix_freebsd.go deleted file mode 100644 index c601a0839d..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/ocis_prefix_freebsd.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -//go:build freebsd - -package prefixes - -// On FreeBSD the `user` namespace is implied through a separate syscall argument -// and will fail with invalid argument when you try to start an xattr name with user. or system. -// For that reason we drop the superfluous user. prefix for FreeBSD specifically. -const ( - OcisPrefix string = "ocis." -) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/prefixes.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/prefixes.go deleted file mode 100644 index 855b3998ef..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes/prefixes.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package prefixes - -import "github.com/opencloud-eu/reva/v2/pkg/storage/utils/ace" - -// Declare a list of xattr keys -// TODO the below comment is currently copied from the owncloud driver, revisit -// Currently,extended file attributes have four separated -// namespaces (user, trusted, security and system) followed by a dot. -// A non root user can only manipulate the user. namespace, which is what -// we will use to store ownCloud specific metadata. To prevent name -// collisions with other apps We are going to introduce a sub namespace -// "user.ocis." in the xattrs_prefix*.go files. -const ( - TypeAttr string = OcisPrefix + "type" - IDAttr string = OcisPrefix + "id" - ParentidAttr string = OcisPrefix + "parentid" - OwnerIDAttr string = OcisPrefix + "owner.id" - OwnerIDPAttr string = OcisPrefix + "owner.idp" - OwnerTypeAttr string = OcisPrefix + "owner.type" - // the base name of the node - // updated when the file is renamed or moved - NameAttr string = OcisPrefix + "name" - - BlobIDAttr string = OcisPrefix + "blobid" - BlobsizeAttr string = OcisPrefix + "blobsize" - - // statusPrefix is the prefix for the node status - StatusPrefix string = OcisPrefix + "nodestatus" - - // scanPrefix is the prefix for the virus scan status and date - ScanStatusPrefix string = OcisPrefix + "scanstatus" - ScanDatePrefix string = OcisPrefix + "scandate" - - // grantPrefix is the prefix for sharing related extended attributes - GrantPrefix string = OcisPrefix + "grant." - GrantUserAcePrefix string = OcisPrefix + "grant." + ace.UserAcePrefix - GrantGroupAcePrefix string = OcisPrefix + "grant." + ace.GroupAcePrefix - MetadataPrefix string = OcisPrefix + "md." - - // favorite flag, per user - FavPrefix string = OcisPrefix + "fav." - - // a temporary etag for a folder that is removed when the mtime propagation happens - TmpEtagAttr string = OcisPrefix + "tmp.etag" - ReferenceAttr string = OcisPrefix + "cs3.ref" // arbitrary metadata - ChecksumPrefix string = OcisPrefix + "cs." // followed by the algorithm, eg. ocis.cs.sha1 - TrashOriginAttr string = OcisPrefix + "trash.origin" // trash origin - - // we use a single attribute to enable or disable propagation of both: synctime and treesize - // The propagation attribute is set to '1' at the top of the (sub)tree. Propagation will stop at - // that node. - PropagationAttr string = OcisPrefix + "propagation" - - // we need mtime to keep mtime in sync with the metadata - MTimeAttr string = OcisPrefix + "mtime" - // the tree modification time of the tree below this node, - // propagated when synctime_accounting is true and - // user.ocis.propagation=1 is set - // stored as a readable time.RFC3339Nano - TreeMTimeAttr string = OcisPrefix + "tmtime" - - // the deletion/disabled time of a space or node - // used to mark space roots as disabled - // stored as a readable time.RFC3339Nano - DTimeAttr string = OcisPrefix + "dtime" - - // the size of the tree below this node, - // propagated when treesize_accounting is true and - // user.ocis.propagation=1 is set - // stored as uint64, little endian - TreesizeAttr string = OcisPrefix + "treesize" - - // the quota for the storage space / tree, regardless who accesses it - QuotaAttr string = OcisPrefix + "quota" - - // the name given to a storage space. It should not contain any semantics as its only purpose is to be read. - SpaceIDAttr string = OcisPrefix + "space.id" - SpaceNameAttr string = OcisPrefix + "space.name" - SpaceTypeAttr string = OcisPrefix + "space.type" - SpaceDescriptionAttr string = OcisPrefix + "space.description" - SpaceReadmeAttr string = OcisPrefix + "space.readme" - SpaceImageAttr string = OcisPrefix + "space.image" - SpaceAliasAttr string = OcisPrefix + "space.alias" -) diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/xattrs_backend.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/xattrs_backend.go deleted file mode 100644 index 619c34b3fe..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/xattrs_backend.go +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package metadata - -import ( - "context" - "io" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/opencloud-eu/reva/v2/pkg/storage/cache" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks" - "github.com/pkg/errors" - "github.com/pkg/xattr" - "github.com/rogpeppe/go-internal/lockedfile" -) - -// XattrsBackend stores the file attributes in extended attributes -type XattrsBackend struct { - rootPath string - metaCache cache.FileMetadataCache -} - -// NewMessageBackend returns a new XattrsBackend instance -func NewXattrsBackend(rootPath string, o cache.Config) XattrsBackend { - return XattrsBackend{ - metaCache: cache.GetFileMetadataCache(o), - } -} - -// Name returns the name of the backend -func (XattrsBackend) Name() string { return "xattrs" } - -// Get an extended attribute value for the given key -// No file locking is involved here as reading a single xattr is -// considered to be atomic. -func (b XattrsBackend) Get(ctx context.Context, path, key string) ([]byte, error) { - attribs := map[string][]byte{} - err := b.metaCache.PullFromCache(b.cacheKey(path), &attribs) - if err == nil && len(attribs[key]) > 0 { - return attribs[key], err - } - - return xattr.Get(path, key) -} - -// GetInt64 reads a string as int64 from the xattrs -func (b XattrsBackend) GetInt64(ctx context.Context, filePath, key string) (int64, error) { - attr, err := b.Get(ctx, filePath, key) - if err != nil { - return 0, err - } - v, err := strconv.ParseInt(string(attr), 10, 64) - if err != nil { - return 0, err - } - return v, nil -} - -// List retrieves a list of names of extended attributes associated with the -// given path in the file system. -func (b XattrsBackend) List(ctx context.Context, filePath string) (attribs []string, err error) { - return b.list(ctx, filePath, true) -} - -func (b XattrsBackend) list(ctx context.Context, filePath string, acquireLock bool) (attribs []string, err error) { - attrs, err := listXattr(ctx, filePath) - if err == nil { - return attrs, nil - } - - // E2BIG means the attribute name list exceeds the maximum size the kernel - // returns (64KiB VFS limit, e.g. on XFS). It is not transient: fail fast - // instead of paying for the locked retry below. - if IsErrTooBig(err) { - return nil, err - } - - // listing xattrs failed, try again, either with lock or without - if acquireLock { - f, err := lockedfile.OpenFile(filePath+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return nil, err - } - defer cleanupLockfile(ctx, f) - - } - return listXattr(ctx, filePath) -} - -// All reads all extended attributes for a node, protected by a -// shared file lock -func (b XattrsBackend) All(ctx context.Context, path string) (map[string][]byte, error) { - return b.getAll(ctx, path, false, true) -} - -func (b XattrsBackend) getAll(ctx context.Context, path string, skipCache, acquireLock bool) (map[string][]byte, error) { - attribs := map[string][]byte{} - - if !skipCache { - err := b.metaCache.PullFromCache(b.cacheKey(path), &attribs) - if err == nil { - return attribs, err - } - } - - attrNames, err := b.list(ctx, path, acquireLock) - if err != nil { - return nil, err - } - - if len(attrNames) == 0 { - return attribs, nil - } - - var ( - xerrs = 0 - xerr error - ) - // error handling: Count if there are errors while reading all attribs. - // if there were any, return an error. - attribs = make(map[string][]byte, len(attrNames)) - for _, name := range attrNames { - var val []byte - if val, xerr = xattr.Get(path, name); xerr != nil && !IsAttrUnset(xerr) { - xerrs++ - } else { - attribs[name] = val - } - } - - if xerrs > 0 { - return nil, errors.Wrap(xerr, "Failed to read all xattrs") - } - - err = b.metaCache.PushToCache(b.cacheKey(path), attribs) - if err != nil { - return nil, err - } - - return attribs, nil -} - -// Set sets one attribute for the given path -func (b XattrsBackend) Set(ctx context.Context, path string, key string, val []byte) (err error) { - return b.SetMultiple(ctx, path, map[string][]byte{key: val}, true) -} - -// SetMultiple sets a set of attribute for the given path -func (b XattrsBackend) SetMultiple(ctx context.Context, path string, attribs map[string][]byte, acquireLock bool) (err error) { - if acquireLock { - err := os.MkdirAll(filepath.Dir(path), 0600) - if err != nil { - return err - } - lockedFile, err := lockedfile.OpenFile(b.LockfilePath(path), os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return err - } - defer cleanupLockfile(ctx, lockedFile) - } - - // error handling: Count if there are errors while setting the attribs. - // if there were any, return an error. - var ( - xerrs = 0 - xerr error - ) - for key, val := range attribs { - if xerr = xattr.Set(path, key, val); xerr != nil { - // log - xerrs++ - } - } - if xerrs > 0 { - return errors.Wrap(xerr, "Failed to set all xattrs") - } - - attribs, err = b.getAll(ctx, path, true, false) - if err != nil { - return err - } - return b.metaCache.PushToCache(b.cacheKey(path), attribs) -} - -// Remove an extended attribute key -func (b XattrsBackend) Remove(ctx context.Context, path string, key string, acquireLock bool) error { - if acquireLock { - lockedFile, err := lockedfile.OpenFile(path+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return err - } - defer cleanupLockfile(ctx, lockedFile) - } - - err := xattr.Remove(path, key) - if err != nil { - return err - } - attribs, err := b.getAll(ctx, path, true, false) - if err != nil { - return err - } - return b.metaCache.PushToCache(b.cacheKey(path), attribs) -} - -// IsMetaFile returns whether the given path represents a meta file -func (XattrsBackend) IsMetaFile(path string) bool { return strings.HasSuffix(path, ".meta.lock") } - -// Purge purges the data of a given path -func (b XattrsBackend) Purge(ctx context.Context, path string) error { - _, err := os.Stat(path) - if err == nil { - attribs, err := b.getAll(ctx, path, true, true) - if err != nil { - return err - } - - for attr := range attribs { - if strings.HasPrefix(attr, prefixes.OcisPrefix) { - err := xattr.Remove(path, attr) - if err != nil { - return err - } - } - } - } - - return b.metaCache.RemoveMetadata(b.cacheKey(path)) -} - -// Rename moves the data for a given path to a new path -func (b XattrsBackend) Rename(oldPath, newPath string) error { - data := map[string][]byte{} - err := b.metaCache.PullFromCache(b.cacheKey(oldPath), &data) - if err == nil { - err = b.metaCache.PushToCache(b.cacheKey(newPath), data) - if err != nil { - return err - } - } - return b.metaCache.RemoveMetadata(b.cacheKey(oldPath)) -} - -// MetadataPath returns the path of the file holding the metadata for the given path -func (XattrsBackend) MetadataPath(path string) string { return path } - -// LockfilePath returns the path of the lock file -func (XattrsBackend) LockfilePath(path string) string { return path + ".mlock" } - -// Lock locks the metadata for the given path -func (b XattrsBackend) Lock(path string) (UnlockFunc, error) { - metaLockPath := b.LockfilePath(path) - mlock, err := lockedfile.OpenFile(metaLockPath, os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return nil, err - } - return func() error { - err := mlock.Close() - if err != nil { - return err - } - return os.Remove(metaLockPath) - }, nil -} - -func cleanupLockfile(ctx context.Context, f *lockedfile.File) { - _ = f.Close() - _ = os.Remove(f.Name()) -} - -// AllWithLockedSource reads all extended attributes from the given reader. -// The path argument is used for storing the data in the cache -func (b XattrsBackend) AllWithLockedSource(ctx context.Context, path string, _ io.Reader) (map[string][]byte, error) { - return b.All(ctx, path) -} - -func (b XattrsBackend) cacheKey(path string) string { - // rootPath is guaranteed to have no trailing slash - // the cache key shouldn't begin with a slash as some stores drop it which can cause - // confusion - return strings.TrimPrefix(path, b.rootPath+"/") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0001_create_spaces_directory_structure.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0001_create_spaces_directory_structure.go deleted file mode 100644 index 398a8f1c32..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0001_create_spaces_directory_structure.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "context" - "errors" - "os" - "path/filepath" - - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" -) - -func init() { - registerMigration("0001", Migration0001{}) -} - -type Migration0001 struct{} - -// Migrate creates the spaces directory structure -func (m Migration0001) Migrate(migrator *Migrator) (Result, error) { - migrator.log.Info().Msg("Migrating spaces directory structure...") - - // create spaces folder and iterate over existing nodes to populate it - nodesPath := filepath.Join(migrator.lu.InternalRoot(), "nodes") - fi, err := os.Stat(nodesPath) - if err == nil && fi.IsDir() { - f, err := os.Open(nodesPath) - if err != nil { - return stateFailed, err - } - nodes, err := f.Readdir(0) - if err != nil { - return stateFailed, err - } - - for _, n := range nodes { - nodePath := filepath.Join(nodesPath, n.Name()) - - attr, err := migrator.lu.MetadataBackend().Get(context.Background(), nodePath, prefixes.ParentidAttr) - if err == nil && string(attr) == node.RootID { - if err := m.moveNode(migrator, n.Name(), n.Name()); err != nil { - migrator.log.Error().Err(err). - Str("space", n.Name()). - Msg("could not move space") - continue - } - m.linkSpaceNode(migrator, "personal", n.Name()) - } - } - // TODO delete nodesPath if empty - } - return stateSucceeded, nil -} - -// Rollback is not implemented -func (Migration0001) Rollback(_ *Migrator) (Result, error) { - return stateFailed, errors.New("rollback not implemented") -} - -func (m Migration0001) moveNode(migrator *Migrator, spaceID, nodeID string) error { - dirPath := filepath.Join(migrator.lu.InternalRoot(), "nodes", nodeID) - f, err := os.Open(dirPath) - if err != nil { - return err - } - children, err := f.Readdir(0) - if err != nil { - return err - } - for _, child := range children { - old := filepath.Join(migrator.lu.InternalRoot(), "nodes", child.Name()) - new := filepath.Join(migrator.lu.InternalRoot(), "spaces", lookup.Pathify(spaceID, 1, 2), "nodes", lookup.Pathify(child.Name(), 4, 2)) - if err := os.Rename(old, new); err != nil { - migrator.log.Error().Err(err). - Str("space", spaceID). - Str("nodes", child.Name()). - Str("oldpath", old). - Str("newpath", new). - Msg("could not rename node") - } - if child.IsDir() { - if err := m.moveNode(migrator, spaceID, child.Name()); err != nil { - return err - } - } - } - return nil -} - -// linkSpace creates a new symbolic link for a space with the given type st, and node id -func (m Migration0001) linkSpaceNode(migrator *Migrator, spaceType, spaceID string) { - spaceTypesPath := filepath.Join(migrator.lu.InternalRoot(), "spacetypes", spaceType, spaceID) - expectedTarget := "../../spaces/" + lookup.Pathify(spaceID, 1, 2) + "/nodes/" + lookup.Pathify(spaceID, 4, 2) - linkTarget, err := os.Readlink(spaceTypesPath) - if errors.Is(err, os.ErrNotExist) { - err = os.Symlink(expectedTarget, spaceTypesPath) - if err != nil { - migrator.log.Error().Err(err). - Str("space_type", spaceType). - Str("space", spaceID). - Msg("could not create symlink") - } - } else { - if err != nil { - migrator.log.Error().Err(err). - Str("space_type", spaceType). - Str("space", spaceID). - Msg("could not read symlink") - } - if linkTarget != expectedTarget { - migrator.log.Warn(). - Str("space_type", spaceType). - Str("space", spaceID). - Str("expected", expectedTarget). - Str("actual", linkTarget). - Msg("expected a different link target") - } - } -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0002_move_spacetypes_to_indexes.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0002_move_spacetypes_to_indexes.go deleted file mode 100644 index 5a81f36aa5..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0002_move_spacetypes_to_indexes.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "errors" - "io" - "os" - "path/filepath" - - "github.com/opencloud-eu/reva/v2/pkg/logger" -) - -func init() { - registerMigration("0002", Migration0002{}) -} - -type Migration0002 struct{} - -// Migrate migrates spacetypes to indexes -func (m Migration0002) Migrate(migrator *Migrator) (Result, error) { - migrator.log.Info().Msg("Migrating space types indexes...") - - spaceTypesPath := filepath.Join(migrator.lu.InternalRoot(), "spacetypes") - fi, err := os.Stat(spaceTypesPath) - if err == nil && fi.IsDir() { - - f, err := os.Open(spaceTypesPath) - if err != nil { - return stateFailed, err - } - spaceTypes, err := f.Readdir(0) - if err != nil { - return stateFailed, err - } - - for _, st := range spaceTypes { - err := m.moveSpaceType(migrator, st.Name()) - if err != nil { - logger.New().Error().Err(err). - Str("space", st.Name()). - Msg("could not move space") - continue - } - } - - // delete spacetypespath - d, err := os.Open(spaceTypesPath) - if err != nil { - logger.New().Error().Err(err). - Str("spacetypesdir", spaceTypesPath). - Msg("could not open spacetypesdir") - return stateFailed, nil - } - defer d.Close() - _, err = d.Readdirnames(1) // Or f.Readdir(1) - if err == io.EOF { - // directory is empty we can delete - err := os.Remove(spaceTypesPath) - if err != nil { - logger.New().Error().Err(err). - Str("spacetypesdir", d.Name()). - Msg("could not delete") - } - } else { - logger.New().Error().Err(err). - Str("spacetypesdir", d.Name()). - Msg("could not delete, not empty") - } - } - return stateSucceeded, nil -} - -// Rollback is not implemented -func (Migration0002) Rollback(_ *Migrator) (Result, error) { - return stateFailed, errors.New("rollback not implemented") -} - -func (m Migration0002) moveSpaceType(migrator *Migrator, spaceType string) error { - dirPath := filepath.Join(migrator.lu.InternalRoot(), "spacetypes", spaceType) - f, err := os.Open(dirPath) - if err != nil { - return err - } - children, err := f.Readdir(0) - if err != nil { - return err - } - for _, child := range children { - old := filepath.Join(migrator.lu.InternalRoot(), "spacetypes", spaceType, child.Name()) - target, err := os.Readlink(old) - if err != nil { - logger.New().Error().Err(err). - Str("space", spaceType). - Str("nodes", child.Name()). - Str("oldLink", old). - Msg("could not read old symlink") - continue - } - newDir := filepath.Join(migrator.lu.InternalRoot(), "indexes", "by-type", spaceType) - if err := os.MkdirAll(newDir, 0700); err != nil { - logger.New().Error().Err(err). - Str("space", spaceType). - Str("nodes", child.Name()). - Str("targetDir", newDir). - Msg("could not read old symlink") - } - newLink := filepath.Join(newDir, child.Name()) - if err := os.Symlink(filepath.Join("..", target), newLink); err != nil { - logger.New().Error().Err(err). - Str("space", spaceType). - Str("nodes", child.Name()). - Str("oldpath", old). - Str("newpath", newLink). - Msg("could not rename node") - continue - } - if err := os.Remove(old); err != nil { - logger.New().Error().Err(err). - Str("space", spaceType). - Str("nodes", child.Name()). - Str("oldLink", old). - Msg("could not remove old symlink") - continue - } - } - if err := os.Remove(dirPath); err != nil { - logger.New().Error().Err(err). - Str("space", spaceType). - Str("dir", dirPath). - Msg("could not remove spaces folder, folder probably not empty") - } - return nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0003_switch_to_messagepack_metadata.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0003_switch_to_messagepack_metadata.go deleted file mode 100644 index 97463b2959..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0003_switch_to_messagepack_metadata.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "context" - "errors" - "io/fs" - "os" - "path/filepath" - "strings" - - "github.com/opencloud-eu/reva/v2/pkg/storage/cache" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" -) - -func init() { - registerMigration("0003", Migration0003{}) -} - -type Migration0003 struct{} - -// Migrate migrates the file metadata to the current backend. -// Only the xattrs -> messagepack path is supported. -func (m Migration0003) Migrate(migrator *Migrator) (Result, error) { - bod := lookup.DetectBackendOnDisk(migrator.lu.InternalRoot()) - if bod == "" { - return stateFailed, errors.New("could not detect metadata backend on disk") - } - - if bod != "xattrs" || migrator.lu.MetadataBackend().Name() != "messagepack" { - return stateSucceededRunAgain, nil - } - - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Migrating to messagepack metadata backend...") - xattrs := metadata.NewXattrsBackend(migrator.lu.InternalRoot(), cache.Config{}) - mpk := metadata.NewMessagePackBackend(migrator.lu.InternalRoot(), cache.Config{}) - - spaces, _ := filepath.Glob(filepath.Join(migrator.lu.InternalRoot(), "spaces", "*", "*")) - for _, space := range spaces { - err := filepath.WalkDir(filepath.Join(space, "nodes"), func(path string, _ fs.DirEntry, err error) error { - // Do not continue on error - if err != nil { - return err - } - - if strings.HasSuffix(path, ".mpk") || strings.HasSuffix(path, ".flock") { - // None of our business - return nil - } - - fi, err := os.Lstat(path) - if err != nil { - return err - } - - if !fi.IsDir() && !fi.Mode().IsRegular() { - return nil - } - - mpkPath := mpk.MetadataPath(path) - _, err = os.Stat(mpkPath) - if err == nil { - return nil - } - - attribs, err := xattrs.All(context.Background(), path) - if err != nil { - migrator.log.Error().Err(err).Str("path", path).Msg("error converting file") - return err - } - if len(attribs) == 0 { - return nil - } - - err = mpk.SetMultiple(context.Background(), path, attribs, false) - if err != nil { - migrator.log.Error().Err(err).Str("path", path).Msg("error setting attributes") - return err - } - - for k := range attribs { - err = xattrs.Remove(context.Background(), path, k, false) - if err != nil { - migrator.log.Debug().Err(err).Str("path", path).Msg("error removing xattr") - } - } - - return nil - }) - if err != nil { - migrator.log.Error().Err(err).Msg("error migrating nodes to messagepack metadata backend") - } - } - - migrator.log.Info().Msg("done.") - return stateSucceeded, nil -} - -// Rollback is not implemented -func (Migration0003) Rollback(_ *Migrator) (Result, error) { - return stateFailed, errors.New("rollback not implemented") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0004_switch_to_messagepack_space_index.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0004_switch_to_messagepack_space_index.go deleted file mode 100644 index 87dd226c0c..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0004_switch_to_messagepack_space_index.go +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "os" - "path/filepath" - "strings" - - "github.com/shamaton/msgpack/v2" -) - -func init() { - registerMigration("0004", Migration0004{}) -} - -type Migration0004 struct{} - -// Migrate migrates the directory tree based space indexes to messagepack -func (Migration0004) Migrate(migrator *Migrator) (Result, error) { - root := migrator.lu.InternalRoot() - - // migrate user indexes - users, err := os.ReadDir(filepath.Join(root, "indexes", "by-user-id")) - if err != nil { - migrator.log.Warn().Err(err).Msg("error listing user indexes") - } - for _, user := range users { - if !user.IsDir() { - continue - } - id := user.Name() - indexPath := filepath.Join(root, "indexes", "by-user-id", id+".mpk") - dirIndexPath := filepath.Join(root, "indexes", "by-user-id", id) - - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Migrating " + indexPath + " to messagepack index format...") - err := migrateSpaceIndex(indexPath, dirIndexPath) - if err != nil { - migrator.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - - // migrate group indexes - groups, err := os.ReadDir(filepath.Join(root, "indexes", "by-group-id")) - if err != nil { - migrator.log.Warn().Err(err).Msg("error listing group indexes") - } - for _, group := range groups { - if !group.IsDir() { - continue - } - id := group.Name() - indexPath := filepath.Join(root, "indexes", "by-group-id", id+".mpk") - dirIndexPath := filepath.Join(root, "indexes", "by-group-id", id) - - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Migrating " + indexPath + " to messagepack index format...") - err := migrateSpaceIndex(indexPath, dirIndexPath) - if err != nil { - migrator.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - - // migrate project indexes - for _, spaceType := range []string{"personal", "project", "share"} { - indexPath := filepath.Join(root, "indexes", "by-type", spaceType+".mpk") - dirIndexPath := filepath.Join(root, "indexes", "by-type", spaceType) - - _, err := os.Stat(dirIndexPath) - if err != nil { - continue - } - - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Migrating " + indexPath + " to messagepack index format...") - err = migrateSpaceIndex(indexPath, dirIndexPath) - if err != nil { - migrator.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - - migrator.log.Info().Msg("done.") - return stateSucceeded, nil -} - -func migrateSpaceIndex(indexPath, dirIndexPath string) error { - links := map[string][]byte{} - m, err := filepath.Glob(dirIndexPath + "/*") - if err != nil { - return err - } - for _, match := range m { - link, err := os.Readlink(match) - if err != nil { - continue - } - links[filepath.Base(match)] = []byte(link) - } - - // rewrite index as file - d, err := msgpack.Marshal(links) - if err != nil { - return err - } - err = os.WriteFile(indexPath, d, 0600) - if err != nil { - return err - } - return os.RemoveAll(dirIndexPath) -} - -// Rollback migrates the directory messagepack indexes to symlinks -func (Migration0004) Rollback(m *Migrator) (Result, error) { - root := m.lu.InternalRoot() - - // migrate user indexes - users, err := filepath.Glob(filepath.Join(root, "indexes", "by-user-id", "*.mpk")) - if err != nil { - m.log.Warn().Err(err).Msg("error listing user indexes") - } - for _, indexPath := range users { - dirIndexPath := strings.TrimSuffix(indexPath, ".mpk") - - m.log.Info().Str("root", m.lu.InternalRoot()).Msg("Migrating " + indexPath + " to symlinks index format...") - err := downSpaceIndex(indexPath, dirIndexPath) - if err != nil { - m.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - - // migrate group indexes - groups, err := filepath.Glob(filepath.Join(root, "indexes", "by-group-id", "*.mpk")) - if err != nil { - m.log.Warn().Err(err).Msg("error listing group indexes") - } - for _, indexPath := range groups { - dirIndexPath := strings.TrimSuffix(indexPath, ".mpk") - - m.log.Info().Str("root", m.lu.InternalRoot()).Msg("Migrating " + indexPath + " to symlinks index format...") - err := downSpaceIndex(indexPath, dirIndexPath) - if err != nil { - m.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - - // migrate project indexes - for _, spaceType := range []string{"personal", "project", "share"} { - indexPath := filepath.Join(root, "indexes", "by-type", spaceType+".mpk") - dirIndexPath := filepath.Join(root, "indexes", "by-type", spaceType) - - _, err := os.Stat(indexPath) - if err != nil || os.IsNotExist(err) { - continue - } - - m.log.Info().Str("root", m.lu.InternalRoot()).Msg("Migrating " + indexPath + " to symlinks index format...") - err = downSpaceIndex(indexPath, dirIndexPath) - if err != nil { - m.log.Error().Err(err).Str("path", dirIndexPath).Msg("error migrating index") - } - } - return stateDown, nil -} - -func downSpaceIndex(indexPath, dirIndexPath string) error { - d, err := os.ReadFile(indexPath) - if err != nil { - return err - } - - links := map[string][]byte{} - err = msgpack.Unmarshal(d, &links) - if err != nil { - return err - } - - err = os.MkdirAll(dirIndexPath, 0700) - if err != nil { - return err - } - for link, target := range links { - err = os.Symlink(string(target), filepath.Join(dirIndexPath, link)) - if err != nil { - return err - } - } - - return os.Remove(indexPath) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0005_fix_messagepack_space_index_format.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0005_fix_messagepack_space_index_format.go deleted file mode 100644 index d3a7bded47..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/0005_fix_messagepack_space_index_format.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "os" - "path/filepath" - - "github.com/shamaton/msgpack/v2" -) - -func init() { - registerMigration("0005", Migration0005{}) -} - -type Migration0005 struct{} - -// Migrate fixes the messagepack space index data structure -func (Migration0005) Migrate(migrator *Migrator) (Result, error) { - root := migrator.lu.InternalRoot() - - indexes, err := filepath.Glob(filepath.Join(root, "indexes", "**", "*.mpk")) - if err != nil { - return stateFailed, err - } - for _, i := range indexes { - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Fixing index format of " + i) - - // Read old-format index - oldData, err := os.ReadFile(i) - if err != nil { - return stateFailed, err - } - oldIndex := map[string][]byte{} - err = msgpack.Unmarshal(oldData, &oldIndex) - if err != nil { - // likely already migrated -> skip - migrator.log.Warn().Str("root", migrator.lu.InternalRoot()).Msg("Invalid index format found in " + i) - continue - } - - // Write new-format index - newIndex := map[string]string{} - for k, v := range oldIndex { - newIndex[k] = string(v) - } - newData, err := msgpack.Marshal(newIndex) - if err != nil { - return stateFailed, err - } - err = os.WriteFile(i, newData, 0600) - if err != nil { - return stateFailed, err - } - } - migrator.log.Info().Msg("done.") - return stateSucceeded, nil -} - -// Rollback rolls back the migration -func (Migration0005) Rollback(migrator *Migrator) (Result, error) { - root := migrator.lu.InternalRoot() - - indexes, err := filepath.Glob(filepath.Join(root, "indexes", "**", "*.mpk")) - if err != nil { - return stateFailed, err - } - for _, i := range indexes { - migrator.log.Info().Str("root", migrator.lu.InternalRoot()).Msg("Fixing index format of " + i) - - oldData, err := os.ReadFile(i) - if err != nil { - return stateFailed, err - } - oldIndex := map[string]string{} - err = msgpack.Unmarshal(oldData, &oldIndex) - if err != nil { - migrator.log.Warn().Str("root", migrator.lu.InternalRoot()).Msg("Invalid index format found in " + i) - continue - } - - // Write new-format index - newIndex := map[string][]byte{} - for k, v := range oldIndex { - newIndex[k] = []byte(v) - } - newData, err := msgpack.Marshal(newIndex) - if err != nil { - return stateFailed, err - } - err = os.WriteFile(i, newData, 0600) - if err != nil { - return stateFailed, err - } - } - migrator.log.Info().Msg("done.") - return stateDown, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/migrator.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/migrator.go deleted file mode 100644 index 482fcd084c..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator/migrator.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package migrator - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "sort" - - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/rs/zerolog" -) - -const ( - statePending = "pending" - stateFailed = "failed" - stateSucceeded = "succeeded" - stateDown = "down" - stateSucceededRunAgain = "runagain" -) - -type migration interface { - Migrate(*Migrator) (Result, error) - Rollback(*Migrator) (Result, error) -} - -var migrations = map[string]migration{} - -type migrationStates map[string]MigrationState - -func registerMigration(name string, migration migration) { - migrations[name] = migration -} - -func allMigrations() []string { - ms := make([]string, 0, len(migrations)) - - for k := range migrations { - ms = append(ms, k) - } - - sort.Strings(ms) - return ms -} - -// MigrationState holds the state of a migration -type MigrationState struct { - State string - Message string -} - -// Result represents the result of a migration run -type Result string - -// Migrator runs migrations on an existing decomposedfs -type Migrator struct { - lu node.PathLookup - states migrationStates - log *zerolog.Logger -} - -// New returns a new Migrator instance -func New(lu node.PathLookup, log *zerolog.Logger) Migrator { - return Migrator{ - lu: lu, - log: log, - } -} - -// Migrations returns the list of migrations and their states -func (m *Migrator) Migrations() (map[string]MigrationState, error) { - err := m.readStates() - if err != nil { - return nil, err - } - - states := map[string]MigrationState{} - for _, migration := range allMigrations() { - if s, ok := m.states[migration]; ok { - states[migration] = s - } else { - states[migration] = MigrationState{ - State: statePending, - } - } - } - - return states, nil -} - -// RunMigration runs or rolls back a migration -func (m *Migrator) RunMigration(id string, rollback bool) error { - if _, ok := migrations[id]; !ok { - return fmt.Errorf("invalid migration '%s'", id) - } - - lock, err := lockedfile.OpenFile(filepath.Join(m.lu.InternalRoot(), ".migrations.lock"), os.O_WRONLY|os.O_CREATE, 0600) - if err != nil { - return err - } - defer lock.Close() - - err = m.readStates() - if err != nil { - return err - } - - var res Result - if !rollback { - m.log.Info().Msg("Running migration " + id + "...") - res, err = migrations[id].Migrate(m) - } else { - m.log.Info().Msg("Rolling back migration " + id + "...") - res, err = migrations[id].Rollback(m) - } - - // write back state - s := m.states[id] - s.State = string(res) - - if err != nil { - m.log.Error().Err(err).Msg("migration " + id + " failed") - s.Message = err.Error() - } - - m.states[id] = s - err = m.writeStates() - if err != nil { - return err - } - m.log.Info().Msg("done") - return nil -} - -// RunMigrations runs all migrations in sequence. Note this sequence must not be changed or it might -// damage existing decomposed fs. -func (m *Migrator) RunMigrations() error { - lock, err := lockedfile.OpenFile(filepath.Join(m.lu.InternalRoot(), ".migrations.lock"), os.O_WRONLY|os.O_CREATE, 0600) - if err != nil { - return err - } - defer lock.Close() - - err = m.readStates() - if err != nil { - return err - } - - for _, migration := range allMigrations() { - s := m.states[migration] - if s.State == stateSucceeded || s.State == stateDown { - continue - } - - res, err := migrations[migration].Migrate(m) - s.State = string(res) - if err != nil { - m.log.Error().Err(err).Msg("migration " + migration + " failed") - s.Message = err.Error() - } - - m.states[migration] = s - err = m.writeStates() - if err != nil { - return err - } - } - return nil -} - -func (m *Migrator) readStates() error { - m.states = migrationStates{} - - d, err := os.ReadFile(filepath.Join(m.lu.InternalRoot(), ".migrations")) - if err != nil { - if !os.IsNotExist(err) { - return err - } - } - - if len(d) > 0 { - err = json.Unmarshal(d, &m.states) - if err != nil { - return err - } - } - - return nil -} - -func (m *Migrator) writeStates() error { - d, err := json.Marshal(m.states) - if err != nil { - m.log.Error().Err(err).Msg("could not marshal migration states") - return nil - } - return os.WriteFile(filepath.Join(m.lu.InternalRoot(), ".migrations"), d, 0600) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/map.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/map.go deleted file mode 100644 index aa1d0cdd24..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/map.go +++ /dev/null @@ -1,45 +0,0 @@ -package mtimesyncedcache - -import "sync" - -type Map[K comparable, V any] struct { - m sync.Map -} - -func (m *Map[K, V]) Delete(key K) { m.m.Delete(key) } - -func (m *Map[K, V]) Load(key K) (value V, ok bool) { - v, ok := m.m.Load(key) - if !ok { - return value, ok - } - return v.(V), ok -} - -func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) { - v, loaded := m.m.LoadAndDelete(key) - if !loaded { - return value, loaded - } - return v.(V), loaded -} - -func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) { - a, loaded := m.m.LoadOrStore(key, value) - return a.(V), loaded -} - -func (m *Map[K, V]) Range(f func(key K, value V) bool) { - m.m.Range(func(key, value any) bool { return f(key.(K), value.(V)) }) -} - -func (m *Map[K, V]) Store(key K, value V) { m.m.Store(key, value) } - -func (m *Map[K, V]) Count() int { - l := 0 - m.Range(func(_ K, _ V) bool { - l++ - return true - }) - return l -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/mtimesyncedcache.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/mtimesyncedcache.go deleted file mode 100644 index 65f7bd3f8d..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache/mtimesyncedcache.go +++ /dev/null @@ -1,59 +0,0 @@ -package mtimesyncedcache - -import ( - "sync" - "time" -) - -type Cache[K comparable, T any] struct { - entries Map[K, *entry[T]] -} - -type entry[T any] struct { - mtime time.Time - value T - - mu sync.Mutex -} - -func New[K comparable, T any]() Cache[K, T] { - return Cache[K, T]{ - entries: Map[K, *entry[T]]{}, - } -} - -func (c *Cache[K, T]) Store(key K, mtime time.Time, value T) error { - c.entries.Store(key, &entry[T]{ - mtime: mtime, - value: value, - }) - return nil -} - -func (c *Cache[K, T]) Load(key K) (T, bool) { - entry, ok := c.entries.Load(key) - if !ok { - var t T - return t, false - } - return entry.value, true -} - -func (c *Cache[K, T]) LoadOrStore(key K, mtime time.Time, f func() (T, error)) (T, error) { - e, _ := c.entries.LoadOrStore(key, &entry[T]{}) - - e.mu.Lock() - defer e.mu.Unlock() - if mtime.After(e.mtime) { - e.mtime = mtime - v, err := f() - if err != nil { - var t T - return t, err - } - e.value = v - c.entries.Store(key, e) - } - - return e.value, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/locks.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/locks.go deleted file mode 100644 index 3dd9ad57cf..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/locks.go +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package node - -import ( - "context" - "encoding/json" - "io/fs" - "os" - "path/filepath" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" -) - -// SetLock sets a lock on the node -func (n *Node) SetLock(ctx context.Context, lock *provider.Lock) error { - ctx, span := tracer.Start(ctx, "SetLock") - defer span.End() - lockFilePath := n.LockFilePath() - - // ensure parent path exists - if err := os.MkdirAll(filepath.Dir(lockFilePath), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating parent folder for lock") - } - - // get file lock, so that nobody can create the lock in the meantime - fileLock, err := filelocks.AcquireWriteLock(n.InternalPath()) - if err != nil { - return err - } - - defer func() { - rerr := filelocks.ReleaseLock(fileLock) - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - // check if already locked - l, err := n.ReadLock(ctx, true) // we already have a write file lock, so ReadLock() would fail to acquire a read file lock -> skip it - switch err.(type) { - case errtypes.NotFound: - // file not locked, continue - case nil: - if l != nil { - return errtypes.PreconditionFailed("already locked") - } - default: - return errors.Wrap(err, "Decomposedfs: could check if file already is locked") - } - - // O_EXCL to make open fail when the file already exists - f, err := os.OpenFile(lockFilePath, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return errors.Wrap(err, "Decomposedfs: could not create lock file") - } - defer f.Close() - - if err := json.NewEncoder(f).Encode(lock); err != nil { - return errors.Wrap(err, "Decomposedfs: could not write lock file") - } - - return err -} - -// ReadLock reads the lock id for a node -func (n Node) ReadLock(ctx context.Context, skipFileLock bool) (*provider.Lock, error) { - ctx, span := tracer.Start(ctx, "ReadLock") - defer span.End() - - // ensure parent path exists - _, subspan := tracer.Start(ctx, "os.MkdirAll") - err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700) - subspan.End() - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error creating parent folder for lock") - } - - // the caller of ReadLock already may hold a file lock - if !skipFileLock { - _, subspan := tracer.Start(ctx, "filelocks.AcquireReadLock") - fileLock, err := filelocks.AcquireReadLock(n.InternalPath()) - subspan.End() - - if err != nil { - return nil, err - } - - defer func() { - _, subspan := tracer.Start(ctx, "filelocks.ReleaseLock") - rerr := filelocks.ReleaseLock(fileLock) - subspan.End() - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - } - - _, subspan = tracer.Start(ctx, "os.Open") - f, err := os.Open(n.LockFilePath()) - subspan.End() - - if err != nil { - if errors.Is(err, fs.ErrNotExist) { - return nil, errtypes.NotFound("no lock found") - } - return nil, errors.Wrap(err, "Decomposedfs: could not open lock file") - } - defer f.Close() - - lock := &provider.Lock{} - if err := json.NewDecoder(f).Decode(lock); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("Decomposedfs: could not decode lock file, ignoring") - return nil, errors.Wrap(err, "Decomposedfs: could not read lock file") - } - - // lock already expired - if lock.Expiration != nil && time.Now().After(time.Unix(int64(lock.Expiration.Seconds), int64(lock.Expiration.Nanos))) { - - _, subspan = tracer.Start(ctx, "os.Remove") - err = os.Remove(f.Name()) - subspan.End() - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: could not remove expired lock file") - } - // we successfully deleted the expired lock - return nil, errtypes.NotFound("no lock found") - } - - return lock, nil -} - -// RefreshLock refreshes the node's lock -func (n *Node) RefreshLock(ctx context.Context, lock *provider.Lock, existingLockID string) error { - ctx, span := tracer.Start(ctx, "RefreshLock") - defer span.End() - - // ensure parent path exists - if err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating parent folder for lock") - } - fileLock, err := filelocks.AcquireWriteLock(n.InternalPath()) - - if err != nil { - return err - } - - defer func() { - rerr := filelocks.ReleaseLock(fileLock) - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - f, err := os.OpenFile(n.LockFilePath(), os.O_RDWR, os.ModeExclusive) - switch { - case errors.Is(err, fs.ErrNotExist): - return errtypes.PreconditionFailed("lock does not exist") - case err != nil: - return errors.Wrap(err, "Decomposedfs: could not open lock file") - } - defer f.Close() - - readLock := &provider.Lock{} - if err := json.NewDecoder(f).Decode(readLock); err != nil { - return errors.Wrap(err, "Decomposedfs: could not read lock") - } - - // check refresh lockID match - if existingLockID == "" && readLock.LockId != lock.LockId { - return errtypes.Aborted("mismatching lock ID") - } - - // check if UnlockAndRelock sends the correct lockID - if existingLockID != "" && readLock.LockId != existingLockID { - return errtypes.Aborted("mismatching existing lock ID") - } - - if ok, err := isLockModificationAllowed(ctx, readLock, lock); !ok { - return err - } - - // Rewind to the beginning of the file before writing a refreshed lock - _, err = f.Seek(0, 0) - if err != nil { - return errors.Wrap(err, "could not seek to the beginning of the lock file") - } - if err := json.NewEncoder(f).Encode(lock); err != nil { - return errors.Wrap(err, "Decomposedfs: could not write lock file") - } - - return err -} - -// Unlock unlocks the node -func (n *Node) Unlock(ctx context.Context, lock *provider.Lock) error { - ctx, span := tracer.Start(ctx, "Unlock") - defer span.End() - - // ensure parent path exists - if err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating parent folder for lock") - } - fileLock, err := filelocks.AcquireWriteLock(n.InternalPath()) - - if err != nil { - return err - } - - defer func() { - rerr := filelocks.ReleaseLock(fileLock) - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - f, err := os.OpenFile(n.LockFilePath(), os.O_RDONLY, os.ModeExclusive) - switch { - case errors.Is(err, fs.ErrNotExist): - return errtypes.Aborted("lock does not exist") - case err != nil: - return errors.Wrap(err, "Decomposedfs: could not open lock file") - } - defer f.Close() - - oldLock := &provider.Lock{} - if err := json.NewDecoder(f).Decode(oldLock); err != nil { - return errors.Wrap(err, "Decomposedfs: could not read lock") - } - - // check lock - if lock == nil || (oldLock.LockId != lock.LockId) { - return errtypes.Locked(oldLock.LockId) - } - - if ok, err := isLockModificationAllowed(ctx, oldLock, lock); !ok { - return err - } - - if err = os.Remove(f.Name()); err != nil { - return errors.Wrap(err, "Decomposedfs: could not remove lock file") - } - return err -} - -// CheckLock compares the context lock with the node lock -func (n *Node) CheckLock(ctx context.Context) error { - ctx, span := tracer.Start(ctx, "CheckLock") - defer span.End() - contextLock, _ := ctxpkg.ContextGetLockID(ctx) - diskLock, _ := n.ReadLock(ctx, false) - if diskLock != nil { - switch contextLock { - case "": - return errtypes.Locked(diskLock.LockId) // no lockid in request - case diskLock.LockId: - return nil // ok - default: - return errtypes.Aborted("mismatching lock") - } - } - if contextLock != "" { - return errtypes.Aborted("not locked") // no lock on disk. why is there a lockid in the context - } - return nil // ok -} - -func readLocksIntoOpaque(ctx context.Context, n *Node, ri *provider.ResourceInfo) error { - lock, err := n.ReadLock(ctx, false) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("Decomposedfs: could not read lock") - return err - } - - // reencode to ensure valid json - var b []byte - if b, err = json.Marshal(lock); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("Decomposedfs: could not marshal locks") - } - if ri.Opaque == nil { - ri.Opaque = &types.Opaque{ - Map: map[string]*types.OpaqueEntry{}, - } - } - ri.Opaque.Map["lock"] = &types.OpaqueEntry{ - Decoder: "json", - Value: b, - } - ri.Lock = lock - return err -} - -func (n *Node) hasLocks(ctx context.Context) bool { - _, err := os.Stat(n.LockFilePath()) // FIXME better error checking - return err == nil -} - -func isLockModificationAllowed(ctx context.Context, oldLock *provider.Lock, newLock *provider.Lock) (bool, error) { - if oldLock.Type == provider.LockType_LOCK_TYPE_SHARED { - return true, nil - } - - appNameEquals := oldLock.AppName == newLock.AppName - if !appNameEquals { - return false, errtypes.PermissionDenied("app names of the locks are mismatching") - } - - var lockUserEquals, contextUserEquals bool - if oldLock.User == nil && newLock.GetUser() == nil { - // no user lock set - lockUserEquals = true - contextUserEquals = true - } else { - lockUserEquals = utils.UserIDEqual(oldLock.User, newLock.GetUser()) - if !lockUserEquals { - return false, errtypes.PermissionDenied("users of the locks are mismatching") - } - - u := ctxpkg.ContextMustGetUser(ctx) - contextUserEquals = utils.UserIDEqual(oldLock.User, u.Id) - if !contextUserEquals { - return false, errtypes.PermissionDenied("lock holder and current user are mismatching") - } - } - - return appNameEquals && lockUserEquals && contextUserEquals, nil - -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node.go deleted file mode 100644 index 27b27d78d2..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node.go +++ /dev/null @@ -1,1561 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package node - -import ( - "context" - "crypto/md5" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "hash/adler32" - "io" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/mime" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/ace" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/grants" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" -) - -var tracer trace.Tracer - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/node") -} - -// Define keys and values used in the node metadata -const ( - LockdiscoveryKey = "lockdiscovery" - FavoriteKey = "http://owncloud.org/ns/favorite" - ShareTypesKey = "http://owncloud.org/ns/share-types" - ChecksumsKey = "http://owncloud.org/ns/checksums" - UserShareType = "0" - QuotaKey = "quota" - - QuotaUnlimited = "0" - QuotaUncalculated = "-1" - QuotaUnknown = "-2" - - // TrashIDDelimiter represents the characters used to separate the nodeid and the deletion time. - TrashIDDelimiter = ".T." - RevisionIDDelimiter = ".REV." - - // RootID defines the root node's ID - RootID = "root" - - // ProcessingStatus is the name of the status when processing a file - ProcessingStatus = "processing:" -) - -type TimeManager interface { - // OverrideMTime overrides the mtime of the node, either on the node itself or in the given attributes, depending on the implementation - OverrideMtime(ctx context.Context, n *Node, attrs *Attributes, mtime time.Time) error - - // MTime returns the mtime of the node - MTime(ctx context.Context, n *Node) (time.Time, error) - // SetMTime sets the mtime of the node - SetMTime(ctx context.Context, n *Node, mtime *time.Time) error - - // TMTime returns the tmtime of the node - TMTime(ctx context.Context, n *Node) (time.Time, error) - // SetTMTime sets the tmtime of the node - SetTMTime(ctx context.Context, n *Node, tmtime *time.Time) error - - // CTime returns the ctime of the node - CTime(ctx context.Context, n *Node) (time.Time, error) - - // DTime returns the deletion time of the node - DTime(ctx context.Context, n *Node) (time.Time, error) - // SetDTime sets the deletion time of the node - SetDTime(ctx context.Context, n *Node, mtime *time.Time) error -} - -// Tree is used to manage a tree hierarchy -type Tree interface { - Setup() error - - GetMD(ctx context.Context, node *Node) (os.FileInfo, error) - ListFolder(ctx context.Context, node *Node) ([]*Node, error) - // CreateHome(owner *userpb.UserId) (n *Node, err error) - CreateDir(ctx context.Context, node *Node) (err error) - TouchFile(ctx context.Context, node *Node, markprocessing bool, mtime string) error - // CreateReference(ctx context.Context, node *Node, targetURI *url.URL) error - Move(ctx context.Context, oldNode *Node, newNode *Node) (err error) - Delete(ctx context.Context, node *Node) (err error) - RestoreRecycleItemFunc(ctx context.Context, spaceid, key, trashPath string, target *Node) (*Node, *Node, func() error, error) - PurgeRecycleItemFunc(ctx context.Context, spaceid, key, purgePath string) (*Node, func() error, error) - - InitNewNode(ctx context.Context, n *Node, fsize uint64) (metadata.UnlockFunc, error) - - // TODO(OCISDEV-901): remove WriteBlob once FinishUploadDecomposed is replaced by the upload coordinator (OCISDEV-900). - WriteBlob(node *Node, source string) error - WriteBlobFromReader(node *Node, r io.Reader, size int64) error - ReadBlob(node *Node) (io.ReadCloser, error) - DeleteBlob(node *Node) error - - BuildSpaceIDIndexEntry(spaceID, nodeID string) string - ResolveSpaceIDIndexEntry(spaceID, entry string) (string, string, error) - - Propagate(ctx context.Context, node *Node, sizeDiff int64) (err error) -} - -// PathLookup defines the interface for the lookup component -type PathLookup interface { - NodeFromSpaceID(ctx context.Context, spaceID string) (n *Node, err error) - NodeFromResource(ctx context.Context, ref *provider.Reference) (*Node, error) - NodeFromID(ctx context.Context, id *provider.ResourceId) (n *Node, err error) - - NodeIDFromParentAndName(ctx context.Context, n *Node, name string) (string, error) - - GenerateSpaceID(spaceType string, owner *userpb.User) (string, error) - - InternalRoot() string - InternalPath(spaceID, nodeID string) string - Path(ctx context.Context, n *Node, hasPermission PermissionFunc) (path string, err error) - MetadataBackend() metadata.Backend - TimeManager() TimeManager - ReadBlobIDAndSizeAttr(ctx context.Context, path string, attrs Attributes) (string, int64, error) - TypeFromPath(ctx context.Context, path string) provider.ResourceType - CopyMetadataWithSourceLock(ctx context.Context, sourcePath, targetPath string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), lockedSource *lockedfile.File, acquireTargetLock bool) (err error) - CopyMetadata(ctx context.Context, src, target string, filter func(attributeName string, value []byte) (newValue []byte, copy bool), acquireTargetLock bool) (err error) -} - -type IDCacher interface { - CacheID(ctx context.Context, spaceID, nodeID, val string) error - GetCachedID(ctx context.Context, spaceID, nodeID string) (string, bool) -} - -// Node represents a node in the tree and provides methods to get a Parent or Child instance -type Node struct { - SpaceID string - ParentID string - ID string - Name string - Blobsize int64 - BlobID string - owner *userpb.UserId - Exists bool - SpaceRoot *Node - - lu PathLookup - xattrsCache map[string][]byte - nodeType *provider.ResourceType -} - -// New returns a new instance of Node -func New(spaceID, id, parentID, name string, blobsize int64, blobID string, t provider.ResourceType, owner *userpb.UserId, lu PathLookup) *Node { - if blobID == "" { - blobID = uuid.New().String() - } - return &Node{ - SpaceID: spaceID, - ID: id, - ParentID: parentID, - Name: name, - Blobsize: blobsize, - owner: owner, - lu: lu, - BlobID: blobID, - nodeType: &t, - } -} - -func (n *Node) MarshalJSON() ([]byte, error) { - return json.Marshal(&struct { - Name string `json:"name"` - ID string `json:"id"` - SpaceID string `json:"spaceID"` - ParentID string `json:"parentID"` - BlobID string `json:"blobID"` - BlobSize int64 `json:"blobSize"` - Exists bool `json:"exists"` - }{ - Name: n.Name, - ID: n.ID, - SpaceID: n.SpaceID, - ParentID: n.ParentID, - BlobID: n.BlobID, - BlobSize: n.Blobsize, - Exists: n.Exists, - }) -} - -// Type returns the node's resource type -func (n *Node) Type(ctx context.Context) provider.ResourceType { - _, span := tracer.Start(ctx, "Type") - defer span.End() - if n.nodeType != nil { - return *n.nodeType - } - - t := provider.ResourceType_RESOURCE_TYPE_INVALID - - // Try to read from xattrs - typeAttr, err := n.XattrInt32(ctx, prefixes.TypeAttr) - if err == nil { - t = provider.ResourceType(typeAttr) - n.nodeType = &t - return t - } - - // Fall back to checking on disk - fi, err := os.Lstat(n.InternalPath()) - if err != nil { - return t - } - - switch { - case fi.IsDir(): - if _, err = n.Xattr(ctx, prefixes.ReferenceAttr); err == nil { - t = provider.ResourceType_RESOURCE_TYPE_REFERENCE - } else { - t = provider.ResourceType_RESOURCE_TYPE_CONTAINER - } - case fi.Mode().IsRegular(): - t = provider.ResourceType_RESOURCE_TYPE_FILE - case fi.Mode()&os.ModeSymlink != 0: - t = provider.ResourceType_RESOURCE_TYPE_SYMLINK - // TODO reference using ext attr on a symlink - // nodeType = provider.ResourceType_RESOURCE_TYPE_REFERENCE - } - n.nodeType = &t - return t -} - -// SetType sets the type of the node. -func (n *Node) SetType(t provider.ResourceType) { - n.nodeType = &t -} - -// NodeMetadata writes the Node metadata to disk and allows passing additional attributes -func (n *Node) NodeMetadata(ctx context.Context) Attributes { - attribs := Attributes{} - attribs.SetInt64(prefixes.TypeAttr, int64(n.Type(ctx))) - attribs.SetString(prefixes.ParentidAttr, n.ParentID) - attribs.SetString(prefixes.NameAttr, n.Name) - if n.Type(ctx) == provider.ResourceType_RESOURCE_TYPE_FILE { - attribs.SetString(prefixes.BlobIDAttr, n.BlobID) - attribs.SetInt64(prefixes.BlobsizeAttr, n.Blobsize) - } - return attribs -} - -// SetOwner sets the space owner on the node -func (n *Node) SetOwner(owner *userpb.UserId) { - n.SpaceRoot.owner = owner -} - -// SpaceOwnerOrManager returns the space owner of the space. If no owner is set -// one of the space managers is returned instead. -func (n *Node) SpaceOwnerOrManager(ctx context.Context) *userpb.UserId { - owner := n.Owner() - if owner != nil && owner.Type != userpb.UserType_USER_TYPE_SPACE_OWNER { - return owner - } - - // We don't have an owner set. Find a manager instead. - grants, err := n.SpaceRoot.ListGrants(ctx) - if err != nil { - return nil - } - for _, grant := range grants { - if grant.Permissions.Stat && grant.Permissions.ListContainer && grant.Permissions.InitiateFileDownload { - return grant.GetGrantee().GetUserId() - } - } - - return nil -} - -// ReadNode creates a new instance from an id and checks if it exists -func ReadNode(ctx context.Context, lu PathLookup, spaceID, nodeID string, canListDisabledSpace bool, spaceRoot *Node, skipParentCheck bool) (*Node, error) { - ctx, span := tracer.Start(ctx, "ReadNode") - defer span.End() - var err error - - if spaceRoot == nil { - // read space root - spaceRoot = &Node{ - SpaceID: spaceID, - lu: lu, - ID: spaceID, - } - spaceRoot.SpaceRoot = spaceRoot - spaceRoot.owner, err = spaceRoot.readOwner(ctx) - switch { - case metadata.IsNotExist(err): - return spaceRoot, nil // swallow not found, the node defaults to exists = false - case err != nil: - return nil, err - } - spaceRoot.Exists = true - - // lookup name in extended attributes - spaceRoot.Name, err = spaceRoot.XattrString(ctx, prefixes.NameAttr) - if err != nil { - return nil, err - } - } - - // TODO ReadNode should not check permissions - if !canListDisabledSpace && spaceRoot.IsDisabled(ctx) { - // no permission = not found - return nil, errtypes.NotFound(spaceID) - } - - // if current user cannot stat the root return not found? - // no for shares the root might be a different resource - - // check if this is a space root - if spaceID == nodeID { - return spaceRoot, nil - } - - // are we reading a revision? - revisionSuffix := "" - if strings.Contains(nodeID, RevisionIDDelimiter) { - // verify revision key format - kp := strings.SplitN(nodeID, RevisionIDDelimiter, 2) - if len(kp) == 2 { - // use the actual node for the metadata lookup - nodeID = kp[0] - // remember revision for blob metadata - revisionSuffix = RevisionIDDelimiter + kp[1] - } - } - - // read node - n := &Node{ - SpaceID: spaceID, - lu: lu, - ID: nodeID, - SpaceRoot: spaceRoot, - } - nodePath := n.InternalPath() - - // append back revision to nodeid, even when returning a not existing node - defer func() { - // when returning errors n is nil - if n != nil { - n.ID += revisionSuffix - } - }() - - attrs, err := n.Xattrs(ctx) - switch { - case metadata.IsNotExist(err): - return n, nil // swallow not found, the node defaults to exists = false - case err != nil: - return nil, err - } - n.Exists = true - - n.Name = attrs.String(prefixes.NameAttr) - n.ParentID = attrs.String(prefixes.ParentidAttr) - if n.ParentID == "" { - d, _ := os.ReadFile(lu.MetadataBackend().MetadataPath(n.InternalPath())) - if _, ok := lu.MetadataBackend().(metadata.MessagePackBackend); ok { - appctx.GetLogger(ctx).Error().Str("path", n.InternalPath()).Str("nodeid", n.ID).Interface("attrs", attrs).Bytes("messagepack", d).Msg("missing parent id") - } - return nil, errtypes.InternalError("Missing parent ID on node") - } - - if revisionSuffix == "" { - n.BlobID, n.Blobsize, err = lu.ReadBlobIDAndSizeAttr(ctx, nodePath, attrs) - if err != nil { - return nil, err - } - } else { - n.BlobID, n.Blobsize, err = lu.ReadBlobIDAndSizeAttr(ctx, nodePath+revisionSuffix, nil) - if err != nil { - return nil, err - } - } - - return n, nil -} - -// Child returns the child node with the given name -func (n *Node) Child(ctx context.Context, name string) (*Node, error) { - ctx, span := tracer.Start(ctx, "Child") - defer span.End() - - spaceID := n.SpaceID - if spaceID == "" && n.ParentID == "root" { - spaceID = n.ID - } else if n.SpaceRoot != nil { - spaceID = n.SpaceRoot.ID - } - c := &Node{ - SpaceID: spaceID, - lu: n.lu, - ParentID: n.ID, - Name: name, - SpaceRoot: n.SpaceRoot, - } - - nodeID, err := n.lu.NodeIDFromParentAndName(ctx, n, name) - switch { - case metadata.IsNotExist(err) || metadata.IsNotDir(err): - return c, nil // if the file does not exist we return a node that has Exists = false - case err != nil: - return nil, err - } - - c, err = ReadNode(ctx, n.lu, spaceID, nodeID, false, n.SpaceRoot, true) - if err != nil { - return nil, errors.Wrap(err, "could not read child node") - } - - return c, nil -} - -// ParentWithReader returns the parent node -func (n *Node) ParentWithReader(ctx context.Context, r io.Reader) (*Node, error) { - _, span := tracer.Start(ctx, "ParentWithReader") - defer span.End() - if n.ParentID == "" { - return nil, fmt.Errorf("decomposedfs: root has no parent") - } - p := &Node{ - SpaceID: n.SpaceID, - lu: n.lu, - ID: n.ParentID, - SpaceRoot: n.SpaceRoot, - } - - // fill metadata cache using the reader - attrs, err := p.XattrsWithReader(ctx, r) - switch { - case metadata.IsNotExist(err): - return p, nil // swallow not found, the node defaults to exists = false - case err != nil: - return nil, err - } - p.Exists = true - - p.Name = attrs.String(prefixes.NameAttr) - p.ParentID = attrs.String(prefixes.ParentidAttr) - - return p, err -} - -// Parent returns the parent node -func (n *Node) Parent(ctx context.Context) (p *Node, err error) { - return n.ParentWithReader(ctx, nil) -} - -// Owner returns the space owner -func (n *Node) Owner() *userpb.UserId { - return n.SpaceRoot.owner -} - -// readOwner reads the owner from the extended attributes of the space root -// in case either owner id or owner idp are unset we return an error and an empty owner object -func (n *Node) readOwner(ctx context.Context) (*userpb.UserId, error) { - owner := &userpb.UserId{} - - // lookup parent id in extended attributes - var attr string - var err error - // lookup ID in extended attributes - attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerIDAttr) - switch { - case err == nil: - owner.OpaqueId = attr - case metadata.IsAttrUnset(err): - // ignore - default: - return nil, err - } - - // lookup IDP in extended attributes - attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerIDPAttr) - switch { - case err == nil: - owner.Idp = attr - case metadata.IsAttrUnset(err): - // ignore - default: - return nil, err - } - - // lookup type in extended attributes - attr, err = n.SpaceRoot.XattrString(ctx, prefixes.OwnerTypeAttr) - switch { - case err == nil: - owner.Type = utils.UserTypeMap(attr) - case metadata.IsAttrUnset(err): - // ignore - default: - return nil, err - } - - // owner is an optional property - if owner.Idp == "" && owner.OpaqueId == "" { - return nil, nil - } - return owner, nil -} - -// PermissionSet returns the permission set and an accessDenied flag -// for the current user -// the parent nodes are not taken into account -// accessDenied is separate from the resource permissions -// because we only support full denials -func (n *Node) PermissionSet(ctx context.Context) (*provider.ResourcePermissions, bool) { - u, ok := ctxpkg.ContextGetUser(ctx) - if !ok { - appctx.GetLogger(ctx).Debug().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Msg("no user in context, returning default permissions") - return NoPermissions(), false - } - if utils.UserEqual(u.Id, n.SpaceRoot.Owner()) { - return OwnerPermissions(), false - } - // read the permissions for the current user from the acls of the current node - if np, accessDenied, err := n.ReadUserPermissions(ctx, u); err == nil { - return np, accessDenied - } - // be defensive, we could have access via another grant - return NoPermissions(), true -} - -// InternalPath returns the internal path of the Node -func (n *Node) InternalPath() string { - return n.lu.InternalPath(n.SpaceID, n.ID) -} - -// ParentPath returns the internal path of the parent of the current node -func (n *Node) ParentPath() string { - return n.lu.InternalPath(n.SpaceID, n.ParentID) -} - -// LockFilePath returns the internal path of the lock file of the node -func (n *Node) LockFilePath() string { - return n.InternalPath() + ".lock" -} - -// CalculateEtag returns a hash of fileid + tmtime (or mtime) -func CalculateEtag(id string, tmTime time.Time) (string, error) { - h := md5.New() - if _, err := io.WriteString(h, id); err != nil { - return "", err - } - /* TODO we could strengthen the etag by adding the blobid, but then all etags would change. we would need a legacy etag check as well - if _, err := io.WriteString(h, n.BlobID); err != nil { - return "", err - } - */ - if tb, err := tmTime.UTC().MarshalBinary(); err == nil { - if _, err := h.Write(tb); err != nil { - return "", err - } - } else { - return "", err - } - return fmt.Sprintf(`"%x"`, h.Sum(nil)), nil -} - -// SetMtimeString sets the mtime and atime of a node to the unixtime parsed from the given string -func (n *Node) SetMtimeString(ctx context.Context, mtime string) error { - mt, err := utils.MTimeToTime(mtime) - if err != nil { - return err - } - return n.SetMtime(ctx, &mt) -} - -// SetMTime writes the UTC mtime to the extended attributes or removes the attribute if nil is passed -func (n *Node) SetMtime(ctx context.Context, t *time.Time) (err error) { - if t == nil { - return n.RemoveXattr(ctx, prefixes.MTimeAttr, true) - } - return n.SetXattrString(ctx, prefixes.MTimeAttr, t.UTC().Format(time.RFC3339Nano)) -} - -// SetEtag sets the temporary etag of a node if it differs from the current etag -func (n *Node) SetEtag(ctx context.Context, val string) (err error) { - sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() - var tmTime time.Time - if tmTime, err = n.GetTMTime(ctx); err != nil { - return - } - var etag string - if etag, err = CalculateEtag(n.ID, tmTime); err != nil { - return - } - - // sanitize etag - val = fmt.Sprintf("\"%s\"", strings.Trim(val, "\"")) - if etag == val { - sublog.Debug(). - Str("etag", val). - Msg("ignoring request to update identical etag") - return nil - } - // etag is only valid until the calculated etag changes, is part of propagation - return n.SetXattrString(ctx, prefixes.TmpEtagAttr, val) -} - -// SetFavorite sets the favorite for the current user -// TODO we should not mess with the user here ... the favorites is now a user specific property for a file -// that cannot be mapped to extended attributes without leaking who has marked a file as a favorite -// it is a specific case of a tag, which is user individual as well -// TODO there are different types of tags -// 1. public that are managed by everyone -// 2. private tags that are only visible to the user -// 3. system tags that are only visible to the system -// 4. group tags that are only visible to a group ... -// urgh ... well this can be solved using different namespaces -// 1. public = p: -// 2. private = u:: for user specific -// 3. system = s: for system -// 4. group = g:: -// 5. app? = a:: for apps? -// obviously this only is secure when the u/s/g/a namespaces are not accessible by users in the filesystem -// public tags can be mapped to extended attributes -func (n *Node) SetFavorite(ctx context.Context, uid *userpb.UserId, val string) error { - // the favorite flag is specific to the user, so we need to incorporate the userid - fa := fmt.Sprintf("%s:%s:%s@%s", prefixes.FavPrefix, utils.UserTypeToString(uid.GetType()), uid.GetOpaqueId(), uid.GetIdp()) - return n.SetXattrString(ctx, fa, val) -} - -// IsDir returns true if the node is a directory -func (n *Node) IsDir(ctx context.Context) bool { - attr, _ := n.XattrInt32(ctx, prefixes.TypeAttr) - return attr == int32(provider.ResourceType_RESOURCE_TYPE_CONTAINER) -} - -// AsResourceInfo return the node as CS3 ResourceInfo -func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissions, mdKeys, fieldMask []string, returnBasename bool) (ri *provider.ResourceInfo, err error) { - sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() - - var fn string - nodeType := n.Type(ctx) - - var target string - if nodeType == provider.ResourceType_RESOURCE_TYPE_REFERENCE { - target, _ = n.XattrString(ctx, prefixes.ReferenceAttr) - } - - id := &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID} - - switch { - case n.IsSpaceRoot(ctx): - fn = "." // space roots do not have a path as they are referencing themselves - case returnBasename: - fn = n.Name - default: - fn, err = n.lu.Path(ctx, n, NoCheck) - if err != nil { - return nil, err - } - } - - ri = &provider.ResourceInfo{ - Id: id, - Path: fn, - Type: nodeType, - MimeType: mime.Detect(nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER, fn), - Size: uint64(n.Blobsize), - Target: target, - PermissionSet: rp, - Owner: n.Owner(), - ParentId: &provider.ResourceId{ - SpaceId: n.SpaceID, - OpaqueId: n.ParentID, - }, - Name: n.Name, - } - - if n.IsProcessing(ctx) { - ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "status", "processing") - } - - if nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER { - ts, err := n.GetTreeSize(ctx) - if err == nil { - ri.Size = ts - } else { - ri.Size = 0 // make dirs always return 0 if it is unknown - sublog.Debug().Err(err).Msg("could not read treesize") - } - } - - // TODO make etag of files use fileid and checksum - - var tmTime time.Time - if tmTime, err = n.GetTMTime(ctx); err != nil { - sublog.Debug().Err(err).Msg("could not get tmtime") - } - - // use temporary etag if it is set - if b, err := n.XattrString(ctx, prefixes.TmpEtagAttr); err == nil && b != "" { - ri.Etag = fmt.Sprintf(`"%x"`, b) - } else if ri.Etag, err = CalculateEtag(n.ID, tmTime); err != nil { - sublog.Debug().Err(err).Msg("could not calculate etag") - } - - // mtime uses tmtime if present - // TODO expose mtime and tmtime separately? - un := tmTime.UnixNano() - ri.Mtime = &types.Timestamp{ - Seconds: uint64(un / 1000000000), - Nanos: uint32(un % 1000000000), - } - - mdKeysMap := make(map[string]struct{}) - for _, k := range mdKeys { - mdKeysMap[k] = struct{}{} - } - - var returnAllMetadata bool - if _, ok := mdKeysMap["*"]; len(mdKeys) == 0 || ok { - returnAllMetadata = true - } - - metadata := map[string]string{} - - fieldMaskKeysMap := make(map[string]struct{}) - for _, k := range fieldMask { - fieldMaskKeysMap[k] = struct{}{} - } - - var returnAllFields bool - if _, ok := fieldMaskKeysMap["*"]; len(fieldMask) == 0 || ok { - returnAllFields = true - } - - // read favorite flag for the current user - if _, ok := mdKeysMap[FavoriteKey]; returnAllMetadata || ok { - favorite := "" - if u, ok := ctxpkg.ContextGetUser(ctx); ok { - // the favorite flag is specific to the user, so we need to incorporate the userid - if uid := u.GetId(); uid != nil { - fa := fmt.Sprintf("%s:%s:%s@%s", prefixes.FavPrefix, utils.UserTypeToString(uid.GetType()), uid.GetOpaqueId(), uid.GetIdp()) - if val, err := n.XattrString(ctx, fa); err == nil { - sublog.Debug(). - Str("favorite", fa). - Msg("found favorite flag") - favorite = val - } - } else { - sublog.Error().Err(errtypes.UserRequired("userrequired")).Msg("user has no id") - } - } else { - sublog.Error().Err(errtypes.UserRequired("userrequired")).Msg("error getting user from ctx") - } - metadata[FavoriteKey] = favorite - } - // read locks - // FIXME move to fieldmask - if _, ok := mdKeysMap[LockdiscoveryKey]; returnAllMetadata || ok { - if n.hasLocks(ctx) { - err = readLocksIntoOpaque(ctx, n, ri) - if err != nil { - sublog.Debug().Err(errtypes.InternalError("lockfail")) - } - } - } - - // share indicator - if _, ok := fieldMaskKeysMap["share-types"]; returnAllFields || ok { - granteeTypes := n.getGranteeTypes(ctx) - if len(granteeTypes) > 0 { - // TODO add optional property to CS3 ResourceInfo to transport grants? - var s strings.Builder - first := true - for _, t := range granteeTypes { - if !first { - s.WriteString(",") - } else { - first = false - } - s.WriteString(strconv.Itoa(int(t))) - } - ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "share-types", s.String()) - } - } - - // checksums - // FIXME move to fieldmask - if _, ok := mdKeysMap[ChecksumsKey]; (nodeType == provider.ResourceType_RESOURCE_TYPE_FILE) && (returnAllMetadata || ok) { - // TODO which checksum was requested? sha1 adler32 or md5? for now hardcode sha1? - // TODO make ResourceInfo carry multiple checksums - n.readChecksumIntoResourceChecksum(ctx, storageprovider.XSSHA1, ri) - n.readChecksumIntoOpaque(ctx, storageprovider.XSMD5, ri) - n.readChecksumIntoOpaque(ctx, storageprovider.XSAdler32, ri) - } - // quota - // FIXME move to fieldmask - if _, ok := mdKeysMap[QuotaKey]; (nodeType == provider.ResourceType_RESOURCE_TYPE_CONTAINER) && returnAllMetadata || ok { - if n.SpaceRoot != nil && n.SpaceRoot.InternalPath() != "" { - n.SpaceRoot.readQuotaIntoOpaque(ctx, ri) - } - } - - // only read the requested metadata attributes - attrs, err := n.Xattrs(ctx) - if err != nil { - sublog.Error().Err(err).Msg("error getting list of extended attributes") - } else { - for key, value := range attrs { - // filter out non-custom properties - if !strings.HasPrefix(key, prefixes.MetadataPrefix) { - continue - } - // only read when key was requested - k := key[len(prefixes.MetadataPrefix):] - if _, ok := mdKeysMap[k]; returnAllMetadata || ok { - metadata[k] = string(value) - } - - } - } - ri.ArbitraryMetadata = &provider.ArbitraryMetadata{ - Metadata: metadata, - } - - // add virusscan information - if scanned, _, date := n.ScanData(ctx); scanned { - ri.Opaque = utils.AppendPlainToOpaque(ri.Opaque, "scantime", date.Format(time.RFC3339Nano)) - } - - sublog.Debug(). - Interface("ri", ri). - Msg("AsResourceInfo") - - return ri, nil -} - -func (n *Node) readChecksumIntoResourceChecksum(ctx context.Context, algo string, ri *provider.ResourceInfo) { - v, err := n.Xattr(ctx, prefixes.ChecksumPrefix+algo) - switch { - case err == nil: - ri.Checksum = &provider.ResourceChecksum{ - Type: storageprovider.PKG2GRPCXS(algo), - Sum: hex.EncodeToString(v), - } - case metadata.IsAttrUnset(err): - appctx.GetLogger(ctx).Debug().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("checksum not set") - default: - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("could not read checksum") - } -} - -func (n *Node) readChecksumIntoOpaque(ctx context.Context, algo string, ri *provider.ResourceInfo) { - v, err := n.Xattr(ctx, prefixes.ChecksumPrefix+algo) - switch { - case err == nil: - if ri.Opaque == nil { - ri.Opaque = &types.Opaque{ - Map: map[string]*types.OpaqueEntry{}, - } - } - ri.Opaque.Map[algo] = &types.OpaqueEntry{ - Decoder: "plain", - Value: []byte(hex.EncodeToString(v)), - } - case metadata.IsAttrUnset(err): - appctx.GetLogger(ctx).Debug().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("checksum not set") - default: - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Str("algorithm", algo).Msg("could not read checksum") - } -} - -// quota is always stored on the root node -func (n *Node) readQuotaIntoOpaque(ctx context.Context, ri *provider.ResourceInfo) { - v, err := n.XattrString(ctx, prefixes.QuotaAttr) - switch { - case err == nil: - // make sure we have a proper signed int - // we use the same magic numbers to indicate: - // -1 = uncalculated - // -2 = unknown - // -3 = unlimited - if _, err := strconv.ParseInt(v, 10, 64); err == nil { - if ri.Opaque == nil { - ri.Opaque = &types.Opaque{ - Map: map[string]*types.OpaqueEntry{}, - } - } - ri.Opaque.Map[QuotaKey] = &types.OpaqueEntry{ - Decoder: "plain", - Value: []byte(v), - } - } else { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Str("quota", v).Msg("malformed quota") - } - case metadata.IsAttrUnset(err): - appctx.GetLogger(ctx).Debug().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Msg("quota not set") - default: - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("nodepath", n.InternalPath()).Msg("could not read quota") - } -} - -// HasPropagation checks if the propagation attribute exists and is set to "1" -func (n *Node) HasPropagation(ctx context.Context) (propagation bool) { - if b, err := n.XattrString(ctx, prefixes.PropagationAttr); err == nil { - return b == "1" - } - return false -} - -// IsDisabled returns true when the node has a dmtime attribute set -// only used to check if a space is disabled -// FIXME confusing with the trash logic -func (n *Node) IsDisabled(ctx context.Context) bool { - if _, err := n.GetDTime(ctx); err == nil { - return true - } - return false -} - -// GetTreeSize reads the treesize from the extended attributes -func (n *Node) GetTreeSize(ctx context.Context) (treesize uint64, err error) { - ctx, span := tracer.Start(ctx, "GetTreeSize") - defer span.End() - s, err := n.XattrUint64(ctx, prefixes.TreesizeAttr) - if err != nil { - return 0, err - } - return s, nil -} - -// SetTreeSize writes the treesize to the extended attributes -func (n *Node) SetTreeSize(ctx context.Context, ts uint64) (err error) { - return n.SetXattrString(ctx, prefixes.TreesizeAttr, strconv.FormatUint(ts, 10)) -} - -// GetBlobSize reads the blobsize from the extended attributes -func (n *Node) GetBlobSize(ctx context.Context) (treesize uint64, err error) { - s, err := n.XattrInt64(ctx, prefixes.BlobsizeAttr) - if err != nil { - return 0, err - } - return uint64(s), nil -} - -// SetChecksum writes the checksum with the given checksum type to the extended attributes -func (n *Node) SetChecksum(ctx context.Context, csType string, h hash.Hash) (err error) { - return n.SetXattr(ctx, prefixes.ChecksumPrefix+csType, h.Sum(nil)) -} - -// UnsetTempEtag removes the temporary etag attribute -func (n *Node) UnsetTempEtag(ctx context.Context) (err error) { - return n.RemoveXattr(ctx, prefixes.TmpEtagAttr, true) -} - -func isGrantExpired(g *provider.Grant) bool { - if g.Expiration == nil { - return false - } - return time.Now().After(time.Unix(int64(g.Expiration.Seconds), int64(g.Expiration.Nanos))) -} - -// ReadUserPermissions will assemble the permissions for the current user on the given node without parent nodes -// we indicate if the access was denied by setting a grant with no permissions -func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap *provider.ResourcePermissions, accessDenied bool, err error) { - // check if the current user is the owner - if utils.UserEqual(u.Id, n.Owner()) { - appctx.GetLogger(ctx).Debug().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Msg("user is owner, returning owner permissions") - return OwnerPermissions(), false, nil - } - - ap = &provider.ResourcePermissions{} - - // for an efficient group lookup convert the list of groups to a map - // groups are just strings ... groupnames ... or group ids ??? AAARGH !!! - groupsMap := make(map[string]bool, len(u.Groups)) - for i := range u.Groups { - groupsMap[u.Groups[i]] = true - } - - var g *provider.Grant - - // we read all grantees from the node - var grantees []string - if grantees, err = n.ListGrantees(ctx); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Msg("error listing grantees") - return NoPermissions(), true, err - } - - // instead of making n getxattr syscalls we are going to list the acls and filter them here - // we have two options here: - // 1. we can start iterating over the acls / grants on the node or - // 2. we can iterate over the number of groups - // The current implementation tries to be defensive for cases where users have hundreds or thousands of groups, so we iterate over the existing acls. - userace := prefixes.GrantPrefix + ace.UserAce(u.Id) - userFound := false - for i := range grantees { - switch { - // we only need to find the user once - case !userFound && grantees[i] == userace: - g, err = n.ReadGrant(ctx, grantees[i]) - case strings.HasPrefix(grantees[i], prefixes.GrantGroupAcePrefix): // only check group grantees - gr := strings.TrimPrefix(grantees[i], prefixes.GrantGroupAcePrefix) - if groupsMap[gr] { - g, err = n.ReadGrant(ctx, grantees[i]) - } else { - // no need to check attribute - continue - } - default: - // no need to check attribute - continue - } - - if isGrantExpired(g) { - continue - } - - switch { - case err == nil: - // If all permissions are set to false we have a deny grant - if grants.PermissionsEqual(g.Permissions, &provider.ResourcePermissions{}) { - return NoPermissions(), true, nil - } - AddPermissions(ap, g.GetPermissions()) - case metadata.IsAttrUnset(err): - appctx.GetLogger(ctx).Error().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("grant", grantees[i]).Interface("grantees", grantees).Msg("grant vanished from node after listing") - // continue with next segment - default: - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("grant", grantees[i]).Msg("error reading permissions") - // continue with next segment - } - } - - appctx.GetLogger(ctx).Debug().Interface("permissions", ap).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Interface("user", u).Msg("returning aggregated permissions") - return ap, false, nil -} - -// IsDenied checks if the node was denied to that user -func (n *Node) IsDenied(ctx context.Context) bool { - gs, err := n.ListGrants(ctx) - if err != nil { - // be paranoid, resource is denied - return true - } - - u := ctxpkg.ContextMustGetUser(ctx) - isExecutant := func(g *provider.Grantee) bool { - switch g.GetType() { - case provider.GranteeType_GRANTEE_TYPE_USER: - return g.GetUserId().GetOpaqueId() == u.GetId().GetOpaqueId() - case provider.GranteeType_GRANTEE_TYPE_GROUP: - // check gid - gid := g.GetGroupId().GetOpaqueId() - for _, group := range u.Groups { - if gid == group { - return true - } - - } - return false - default: - return false - } - - } - - for _, g := range gs { - if !isExecutant(g.Grantee) { - continue - } - - if grants.PermissionsEqual(g.Permissions, &provider.ResourcePermissions{}) { - // resource is denied - return true - } - } - - // no deny grants - return false -} - -// ListGrantees lists the grantees of the current node -// We don't want to wast time and memory by creating grantee objects. -// The function will return a list of opaque strings that can be used to make a ReadGrant call -func (n *Node) ListGrantees(ctx context.Context) (grantees []string, err error) { - attrs, err := n.Xattrs(ctx) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Msg("error listing attributes") - return nil, err - } - for name := range attrs { - if strings.HasPrefix(name, prefixes.GrantPrefix) { - grantees = append(grantees, name) - } - } - return -} - -// ReadGrant reads a CS3 grant -func (n *Node) ReadGrant(ctx context.Context, grantee string) (g *provider.Grant, err error) { - xattr, err := n.Xattr(ctx, grantee) - if err != nil { - return nil, err - } - var e *ace.ACE - if e, err = ace.Unmarshal(strings.TrimPrefix(grantee, prefixes.GrantPrefix), xattr); err != nil { - return nil, err - } - return e.Grant(), nil -} - -// ReadGrant reads a CS3 grant -func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) { - - var attr string - if g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP { - attr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId - } else { - attr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId - } - - if err = n.RemoveXattr(ctx, attr, acquireLock); err != nil { - return err - } - - return nil -} - -// Purge removes a node from disk. It does not move it to the trash -func (n *Node) Purge(ctx context.Context) error { - // remove node - if err := utils.RemoveItem(n.InternalPath()); err != nil { - return err - } - - // remove child entry in parent - src := filepath.Join(n.ParentPath(), n.Name) - if err := os.Remove(src); err != nil { - return err - } - - // remove .mpk and .mlock files - return n.lu.MetadataBackend().Purge(ctx, n.InternalPath()) -} - -// ListGrants lists all grants of the current node. -func (n *Node) ListGrants(ctx context.Context) ([]*provider.Grant, error) { - grantees, err := n.ListGrantees(ctx) - if err != nil { - return nil, err - } - - grants := make([]*provider.Grant, 0, len(grantees)) - for _, g := range grantees { - grant, err := n.ReadGrant(ctx, g) - if err != nil { - appctx.GetLogger(ctx). - Error(). - Err(err). - Str("spaceid", n.SpaceID). - Str("nodeid", n.ID). - Str("grantee", g). - Msg("error reading grant") - continue - } - grants = append(grants, grant) - } - return grants, nil -} - -func (n *Node) getGranteeTypes(ctx context.Context) []provider.GranteeType { - types := []provider.GranteeType{} - if g, err := n.ListGrantees(ctx); err == nil { - hasUserShares, hasGroupShares := false, false - for i := range g { - switch { - case !hasUserShares && strings.HasPrefix(g[i], prefixes.GrantUserAcePrefix): - hasUserShares = true - case !hasGroupShares && strings.HasPrefix(g[i], prefixes.GrantGroupAcePrefix): - hasGroupShares = true - case hasUserShares && hasGroupShares: - break - } - } - if hasUserShares { - types = append(types, provider.GranteeType_GRANTEE_TYPE_USER) - } - if hasGroupShares { - types = append(types, provider.GranteeType_GRANTEE_TYPE_GROUP) - } - } - return types -} - -// FindStorageSpaceRoot calls n.Parent() and climbs the tree -// until it finds the space root node and adds it to the node -func (n *Node) FindStorageSpaceRoot(ctx context.Context) error { - if n.SpaceRoot != nil { - return nil - } - var err error - // remember the node we ask for and use parent to climb the tree - parent := n - for { - if parent.IsSpaceRoot(ctx) { - n.SpaceRoot = parent - break - } - if parent, err = parent.Parent(ctx); err != nil { - return err - } - } - return nil -} - -// UnmarkProcessing removes the processing flag from the node -func (n *Node) UnmarkProcessing(ctx context.Context, uploadID string) error { - // we currently have to decrease the counter for every processing run to match the incrases - metrics.UploadProcessing.Sub(1) - - v, _ := n.XattrString(ctx, prefixes.StatusPrefix) - if v != ProcessingStatus+uploadID { - // file started another postprocessing later - do not remove - return nil - } - return n.RemoveXattr(ctx, prefixes.StatusPrefix, true) -} - -// IsProcessing returns true if the node is currently being processed -func (n *Node) IsProcessing(ctx context.Context) bool { - v, err := n.XattrString(ctx, prefixes.StatusPrefix) - return err == nil && strings.HasPrefix(v, ProcessingStatus) -} - -// ProcessingID returns the latest upload session id -func (n *Node) ProcessingID(ctx context.Context) (string, error) { - v, err := n.XattrString(ctx, prefixes.StatusPrefix) - return strings.TrimPrefix(v, ProcessingStatus), err -} - -// IsSpaceRoot checks if the node is a space root -func (n *Node) IsSpaceRoot(ctx context.Context) bool { - return n.ID == n.SpaceID -} - -// SetScanData sets the virus scan info to the node -func (n *Node) SetScanData(ctx context.Context, info string, date time.Time) error { - attribs := Attributes{} - attribs.SetString(prefixes.ScanStatusPrefix, info) - attribs.SetString(prefixes.ScanDatePrefix, date.Format(time.RFC3339Nano)) - return n.SetXattrsWithContext(ctx, attribs, true) -} - -// ScanData returns scanning information of the node -func (n *Node) ScanData(ctx context.Context) (scanned bool, virus string, scantime time.Time) { - ti, _ := n.XattrString(ctx, prefixes.ScanDatePrefix) - if ti == "" { - return // not scanned yet - } - - t, err := time.Parse(time.RFC3339Nano, ti) - if err != nil { - return - } - - i, err := n.XattrString(ctx, prefixes.ScanStatusPrefix) - if err != nil { - return - } - - return true, i, t -} - -// CheckQuota checks if both disk space and available quota are sufficient -// Overwrite must be set to true if the new file replaces the old file e.g. -// when creating a new file version. In such a case the function will -// reduce the used bytes by the old file size and then add the new size. -// If overwrite is false oldSize will be ignored. -var CheckQuota = func(ctx context.Context, spaceRoot *Node, overwrite bool, oldSize, newSize uint64) (quotaSufficient bool, err error) { - used, _ := spaceRoot.GetTreeSize(ctx) - if !enoughDiskSpace(spaceRoot.InternalPath(), newSize) { - return false, errtypes.InsufficientStorage("disk full") - } - quotaByteStr, _ := spaceRoot.XattrString(ctx, prefixes.QuotaAttr) - switch quotaByteStr { - case "": - // if quota is not set, it means unlimited - return true, nil - case QuotaUnlimited: - return true, nil - case QuotaUncalculated: - // treat it as unlimited - return true, nil - case QuotaUnknown: - // treat it as unlimited - return true, nil - } - quotaByte, _ := strconv.ParseUint(quotaByteStr, 10, 64) - if overwrite { - if quotaByte < used-oldSize+newSize { - return false, errtypes.InsufficientStorage("quota exceeded") - } - // if total is smaller than used, total-used could overflow and be bigger than fileSize - } else if newSize > quotaByte-used || quotaByte < used { - return false, errtypes.InsufficientStorage("quota exceeded") - } - return true, nil -} - -func enoughDiskSpace(path string, fileSize uint64) bool { - avalB, err := GetAvailableSize(path) - if err != nil { - return false - } - return avalB > fileSize -} - -// CalculateChecksums calculates the sha1, md5 and adler32 checksums of a file -func CalculateChecksums(ctx context.Context, path string) (hash.Hash, hash.Hash, hash.Hash32, error) { - sha1h := sha1.New() - md5h := md5.New() - adler32h := adler32.New() - - _, subspan := tracer.Start(ctx, "os.Open") - f, err := os.Open(path) - subspan.End() - if err != nil { - return nil, nil, nil, err - } - defer f.Close() - - r1 := io.TeeReader(f, sha1h) - r2 := io.TeeReader(r1, md5h) - - _, subspan = tracer.Start(ctx, "io.Copy") - _, err = io.Copy(adler32h, r2) - subspan.End() - if err != nil { - return nil, nil, nil, err - } - - return sha1h, md5h, adler32h, nil -} - -// GetMTime reads the mtime from the extended attributes -func (n *Node) GetMTime(ctx context.Context) (time.Time, error) { - return n.lu.TimeManager().MTime(ctx, n) -} - -// GetTMTime reads the tmtime from the extended attributes -func (n *Node) GetTMTime(ctx context.Context) (time.Time, error) { - return n.lu.TimeManager().TMTime(ctx, n) -} - -// SetTMTime writes the UTC tmtime to the extended attributes or removes the attribute if nil is passed -func (n *Node) SetTMTime(ctx context.Context, t *time.Time) (err error) { - return n.lu.TimeManager().SetTMTime(ctx, n, t) -} - -// GetDTime reads the dmtime from the extended attributes -func (n *Node) GetDTime(ctx context.Context) (time.Time, error) { - return n.lu.TimeManager().DTime(ctx, n) -} - -// SetDTime writes the UTC dmtime to the extended attributes or removes the attribute if nil is passed -func (n *Node) SetDTime(ctx context.Context, t *time.Time) (err error) { - return n.lu.TimeManager().SetDTime(ctx, n, t) -} - -// RevertUpload reverts the upload that created the given revision: it -// restores the revision onto the node and removes the revision, including its -// metadata sidecars. The node's metadata lock is held for the duration of the -// operation. -func (n *Node) RevertUpload(ctx context.Context, versionID string) error { - if versionID == "" { - return errors.New("empty versionID") - } - - lock, err := lockedfile.OpenFile(n.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return err - } - defer lock.Close() - - revisionPath := n.InternalPath() + RevisionIDDelimiter + versionID - if _, err := os.Stat(revisionPath); err != nil { - appctx.GetLogger(ctx).Error().Str("versionpath", revisionPath).Err(err).Msg("revision does not exist") - return err - } - - if err := n.lu.CopyMetadata(ctx, revisionPath, n.InternalPath(), func(attributeName string, value []byte) (newValue []byte, copy bool) { - return value, strings.HasPrefix(attributeName, prefixes.ChecksumPrefix) || - attributeName == prefixes.TypeAttr || - attributeName == prefixes.BlobIDAttr || - attributeName == prefixes.BlobsizeAttr || - attributeName == prefixes.MTimeAttr - }, false); err != nil { - appctx.GetLogger(ctx).Info().Str("versionpath", revisionPath).Str("nodepath", n.InternalPath()).Err(err).Msg("restoring revision metadata failed") - return err - } - - if err := os.RemoveAll(revisionPath); err != nil { - appctx.GetLogger(ctx).Info().Str("versionpath", revisionPath).Str("nodepath", n.InternalPath()).Err(err).Msg("error removing version") - return err - } - - // remove the revision's metadata sidecars - if err := os.Remove(n.lu.MetadataBackend().MetadataPath(revisionPath)); err != nil { - appctx.GetLogger(ctx).Warn().Err(err).Str("versionpath", revisionPath).Msg("could not delete revision metadata, continuing") - } - if err := os.Remove(n.lu.MetadataBackend().LockfilePath(revisionPath)); err != nil { - appctx.GetLogger(ctx).Warn().Err(err).Str("versionpath", revisionPath).Msg("could not delete revision metadata lockfile, continuing") - } - if err := n.lu.MetadataBackend().Purge(ctx, revisionPath); err != nil { - appctx.GetLogger(ctx).Warn().Err(err).Str("versionpath", revisionPath).Msg("could not purge revision from cache, continuing") - } - return nil -} - -// DeleteRevision deletes a revision of the node and returns the blob id of the -// deleted revision, so that the caller can delete the blob. If versionID is -// empty the node's current revision is deleted: the latest stored revision is -// restored onto the node (or the node is purged when there is none) and the -// processing flag is removed, unstalling the node. No blob is returned in that -// case. -func (n *Node) DeleteRevision(ctx context.Context, versionID string) (string, error) { - if versionID != "" { - return n.deleteRevision(ctx, versionID) - } - - revisionPath, err := n.getLatestRevision(ctx) - if err != nil { - return "", err - } - - if revisionPath == "" { - // there is no revision - delete the node - lock, err := lockedfile.OpenFile(n.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return "", err - } - defer lock.Close() - if err := n.Purge(ctx); err != nil { - appctx.GetLogger(ctx).Info().Str("nodepath", n.InternalPath()).Err(err).Msg("error purging node") - return "", err - } - return "", nil - } - - latestID := strings.TrimPrefix(revisionPath, n.InternalPath()+RevisionIDDelimiter) - if err := n.RevertUpload(ctx, latestID); err != nil { - return "", err - } - - // we just deleted the current revision - remove processing flag if set - if uploadid, err := n.ProcessingID(ctx); err == nil { - return "", n.UnmarkProcessing(ctx, uploadid) - } - return "", nil -} - -// deleteRevision deletes the revision identified by versionID (the timestamp -// following the node's InternalPath + RevisionIDDelimiter) together with its -// metadata sidecars and returns its blob id. It is a no-op if the revision -// does not exist. -func (n *Node) deleteRevision(ctx context.Context, versionID string) (string, error) { - log := appctx.GetLogger(ctx) - - revisionPath := n.InternalPath() + RevisionIDDelimiter + versionID - if _, err := os.Stat(revisionPath); err != nil { - log.Warn().Str("nodeid", n.ID).Str("versionid", versionID).Msg("revision does not exist, nothing to delete") - return "", nil - } - - lock, err := lockedfile.OpenFile(n.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - return "", err - } - defer lock.Close() - - blobID, _, err := n.lu.ReadBlobIDAndSizeAttr(ctx, revisionPath, nil) - if err != nil { - return "", err - } - - if err := os.RemoveAll(revisionPath); err != nil { - return "", err - } - - if err := os.Remove(n.lu.MetadataBackend().MetadataPath(revisionPath)); err != nil { - log.Warn().Err(err).Str("nodeid", n.ID).Str("versionid", versionID).Msg("could not delete revision metadata, continuing") - } - if err := os.Remove(n.lu.MetadataBackend().LockfilePath(revisionPath)); err != nil { - log.Warn().Err(err).Str("nodeid", n.ID).Str("versionid", versionID).Msg("could not delete revision metadata lockfile, continuing") - } - if err := n.lu.MetadataBackend().Purge(ctx, revisionPath); err != nil { - log.Warn().Err(err).Str("nodeid", n.ID).Str("versionid", versionID).Msg("could not purge revision from cache, continuing") - } - - return blobID, nil -} - -func (n *Node) getLatestRevision(ctx context.Context) (string, error) { - revPrefix := n.InternalPath() + RevisionIDDelimiter - revisions, err := filepath.Glob(revPrefix + "*") - if err != nil { - appctx.GetLogger(ctx).Error().Str("nodepath", n.InternalPath()).Err(err).Msg("error reading revisions") - return "", err - } - - revPath, latest := "", time.Time{} - for _, rev := range revisions { - if strings.HasSuffix(rev, ".mpk") || strings.HasSuffix(rev, ".mlock") { - continue - } - revDate, err := time.Parse(time.RFC3339Nano, strings.TrimPrefix(rev, revPrefix)) - if err != nil { - appctx.GetLogger(ctx).Error().Str("nodepath", n.InternalPath()).Err(err).Msg("error parsing revision date") - continue - } - - appctx.GetLogger(ctx).Error().Str("nodepath", n.InternalPath()).Str("revPath", revPath).Interface("time", revDate).Err(err).Msg("error parsing revision date") - if revDate.After(latest) { - latest = revDate - revPath = rev - } - } - return revPath, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_unix.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_unix.go deleted file mode 100644 index 0051557a7e..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_unix.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -//go:build !windows -// +build !windows - -package node - -import ( - "syscall" -) - -// GetAvailableSize stats the filesystem and return the available bytes -func GetAvailableSize(path string) (uint64, error) { - stat := syscall.Statfs_t{} - err := syscall.Statfs(path, &stat) - if err != nil { - return 0, err - } - - // convert stat.Bavail to uint64 because it returns an int64 on freebsd - return uint64(stat.Bavail) * uint64(stat.Bsize), nil //nolint:unconvert -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_windows.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_windows.go deleted file mode 100644 index 55febbbd88..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/node_windows.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -//go:build windows -// +build windows - -package node - -import "golang.org/x/sys/windows" - -// GetAvailableSize stats the filesystem and return the available bytes -func GetAvailableSize(path string) (uint64, error) { - var free, total, avail uint64 - pathPtr, err := windows.UTF16PtrFromString(path) - if err != nil { - return 0, err - } - err = windows.GetDiskFreeSpaceEx(pathPtr, &avail, &total, &free) - if err != nil { - return 0, err - } - return avail, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/permissions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/permissions.go deleted file mode 100644 index 6b1beb37d3..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/permissions.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package node - -import ( - "context" - "strings" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" -) - -// PermissionFunc should return true when the user has permission to access the node -type PermissionFunc func(*Node) bool - -var ( - // NoCheck doesn't check permissions, returns true always - NoCheck PermissionFunc = func(_ *Node) bool { - return true - } -) - -// NoPermissions represents an empty set of permissions -func NoPermissions() *provider.ResourcePermissions { - return &provider.ResourcePermissions{} -} - -// ShareFolderPermissions defines permissions for the shared jail -func ShareFolderPermissions() *provider.ResourcePermissions { - return &provider.ResourcePermissions{ - // read permissions - ListContainer: true, - Stat: true, - InitiateFileDownload: true, - GetPath: true, - GetQuota: true, - ListFileVersions: true, - } -} - -// OwnerPermissions defines permissions for nodes owned by the user -func OwnerPermissions() *provider.ResourcePermissions { - return &provider.ResourcePermissions{ - // all permissions - AddGrant: true, - CreateContainer: true, - Delete: true, - GetPath: true, - GetQuota: true, - InitiateFileDownload: true, - InitiateFileUpload: true, - ListContainer: true, - ListFileVersions: true, - ListGrants: true, - ListRecycle: true, - Move: true, - PurgeRecycle: true, - RemoveGrant: true, - RestoreFileVersion: true, - RestoreRecycleItem: true, - Stat: true, - UpdateGrant: true, - DenyGrant: true, - } -} - -// ServiceAccountPermissions defines the permissions for nodes when requested by a service account -func ServiceAccountPermissions() *provider.ResourcePermissions { - // TODO: Different permissions for different service accounts - return &provider.ResourcePermissions{ - Stat: true, - ListContainer: true, - GetPath: true, // for search index - InitiateFileUpload: true, // for personal data export - InitiateFileDownload: true, // for full-text-search - RemoveGrant: true, // for share expiry - ListRecycle: true, // for purge-trash-bin command - PurgeRecycle: true, // for purge-trash-bin command - RestoreRecycleItem: true, // for cli restore command - Delete: true, // for cli restore command with replace option - CreateContainer: true, // for space provisioning - AddGrant: true, // for initial project space member assignment - } -} - -// Permissions implements permission checks -type Permissions struct { - lu PathLookup -} - -// NewPermissions returns a new Permissions instance -func NewPermissions(lu PathLookup) *Permissions { - return &Permissions{ - lu: lu, - } -} - -// AssemblePermissions will assemble the permissions for the current user on the given node, taking into account all parent nodes -func (p *Permissions) AssemblePermissions(ctx context.Context, n *Node) (ap *provider.ResourcePermissions, err error) { - return p.assemblePermissions(ctx, n, true) -} - -// AssembleTrashPermissions will assemble the permissions for the current user on the given node, taking into account all parent nodes -func (p *Permissions) AssembleTrashPermissions(ctx context.Context, n *Node) (ap *provider.ResourcePermissions, err error) { - return p.assemblePermissions(ctx, n, false) -} - -// assemblePermissions will assemble the permissions for the current user on the given node, taking into account all parent nodes -func (p *Permissions) assemblePermissions(ctx context.Context, n *Node, failOnTrashedSubtree bool) (ap *provider.ResourcePermissions, err error) { - u, ok := ctxpkg.ContextGetUser(ctx) - if !ok { - return NoPermissions(), nil - } - - if u.GetId().GetType() == userpb.UserType_USER_TYPE_SERVICE { - return ServiceAccountPermissions(), nil - } - - // are we reading a revision? - if strings.Contains(n.ID, RevisionIDDelimiter) { - // verify revision key format - kp := strings.SplitN(n.ID, RevisionIDDelimiter, 2) - if len(kp) != 2 { - return NoPermissions(), errtypes.NotFound(n.ID) - } - // use the actual node for the permission assembly - n.ID = kp[0] - } - - // determine root - rn := n.SpaceRoot - cn := n - ap = &provider.ResourcePermissions{} - - // for an efficient group lookup convert the list of groups to a map - // groups are just strings ... groupnames ... or group ids ??? AAARGH !!! - groupsMap := make(map[string]bool, len(u.Groups)) - for i := range u.Groups { - groupsMap[u.Groups[i]] = true - } - - // for all segments, starting at the leaf - for cn.ID != rn.ID { - if np, accessDenied, err := cn.ReadUserPermissions(ctx, u); err == nil { - // check if we have a denial on this node - if accessDenied { - return np, nil - } - AddPermissions(ap, np) - } else { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", cn.SpaceID).Str("nodeid", cn.ID).Msg("error reading permissions") - // continue with next segment - } - - if cn, err = cn.Parent(ctx); err != nil { - // We get an error but get a parent, but can not read it from disk (eg. it has been deleted already) - if cn != nil { - return ap, errors.Wrap(err, "Decomposedfs: error getting parent for node "+cn.ID) - } - // We do not have a parent, so we assume the next valid parent is the spaceRoot (which must always exist) - cn = n.SpaceRoot - } - if failOnTrashedSubtree && !cn.Exists { - return NoPermissions(), errtypes.NotFound(n.ID) - } - - } - - // for the root node - if np, accessDenied, err := cn.ReadUserPermissions(ctx, u); err == nil { - // check if we have a denial on this node - if accessDenied { - return np, nil - } - AddPermissions(ap, np) - } else { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", cn.SpaceID).Str("nodeid", cn.ID).Msg("error reading root node permissions") - } - - // check if the current user is the owner - if utils.UserIDEqual(u.Id, n.Owner()) { - return OwnerPermissions(), nil - } - - appctx.GetLogger(ctx).Debug().Interface("permissions", ap).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Interface("user", u).Msg("returning agregated permissions") - return ap, nil -} - -// AddPermissions merges a set of permissions into another -// TODO we should use a bitfield for this ... -func AddPermissions(l *provider.ResourcePermissions, r *provider.ResourcePermissions) { - l.AddGrant = l.AddGrant || r.AddGrant - l.CreateContainer = l.CreateContainer || r.CreateContainer - l.Delete = l.Delete || r.Delete - l.GetPath = l.GetPath || r.GetPath - l.GetQuota = l.GetQuota || r.GetQuota - l.InitiateFileDownload = l.InitiateFileDownload || r.InitiateFileDownload - l.InitiateFileUpload = l.InitiateFileUpload || r.InitiateFileUpload - l.ListContainer = l.ListContainer || r.ListContainer - l.ListFileVersions = l.ListFileVersions || r.ListFileVersions - l.ListGrants = l.ListGrants || r.ListGrants - l.ListRecycle = l.ListRecycle || r.ListRecycle - l.Move = l.Move || r.Move - l.PurgeRecycle = l.PurgeRecycle || r.PurgeRecycle - l.RemoveGrant = l.RemoveGrant || r.RemoveGrant - l.RestoreFileVersion = l.RestoreFileVersion || r.RestoreFileVersion - l.RestoreRecycleItem = l.RestoreRecycleItem || r.RestoreRecycleItem - l.Stat = l.Stat || r.Stat - l.UpdateGrant = l.UpdateGrant || r.UpdateGrant - l.DenyGrant = l.DenyGrant || r.DenyGrant -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/xattrs.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/xattrs.go deleted file mode 100644 index b34d6fb264..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node/xattrs.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package node - -import ( - "context" - "io" - "io/fs" - "strconv" - "time" - - "github.com/pkg/xattr" -) - -// Attributes is a map of string keys and byte array values -type Attributes map[string][]byte - -// String reads a String value -func (md Attributes) String(key string) string { - return string(md[key]) -} - -// SetString sets a string value -func (md Attributes) SetString(key, val string) { - md[key] = []byte(val) -} - -// Int64 reads an int64 value -func (md Attributes) Int64(key string) (int64, error) { - return strconv.ParseInt(string(md[key]), 10, 64) -} - -// SetInt64 sets an int64 value -func (md Attributes) SetInt64(key string, val int64) { - md[key] = []byte(strconv.FormatInt(val, 10)) -} - -// UInt64 reads an uint64 value -func (md Attributes) UInt64(key string) (uint64, error) { - return strconv.ParseUint(string(md[key]), 10, 64) -} - -// SetInt64 sets an uint64 value -func (md Attributes) SetUInt64(key string, val uint64) { - md[key] = []byte(strconv.FormatUint(val, 10)) -} - -// Time reads a time value -func (md Attributes) Time(key string) (time.Time, error) { - return time.Parse(time.RFC3339Nano, string(md[key])) -} - -// SetXattrs sets multiple extended attributes on the write-through cache/node -func (n *Node) SetXattrsWithContext(ctx context.Context, attribs map[string][]byte, acquireLock bool) (err error) { - _, span := tracer.Start(ctx, "SetXattrsWithContext") - defer span.End() - if n.xattrsCache != nil { - for k, v := range attribs { - n.xattrsCache[k] = v - } - } - - return n.lu.MetadataBackend().SetMultiple(ctx, n.InternalPath(), attribs, acquireLock) -} - -// SetXattrs sets multiple extended attributes on the write-through cache/node -func (n *Node) SetXattrs(attribs map[string][]byte, acquireLock bool) (err error) { - return n.SetXattrsWithContext(context.Background(), attribs, acquireLock) -} - -// SetXattr sets an extended attribute on the write-through cache/node -func (n *Node) SetXattr(ctx context.Context, key string, val []byte) (err error) { - if n.xattrsCache != nil { - n.xattrsCache[key] = val - } - - return n.lu.MetadataBackend().Set(ctx, n.InternalPath(), key, val) -} - -// SetXattrString sets a string extended attribute on the write-through cache/node -func (n *Node) SetXattrString(ctx context.Context, key, val string) (err error) { - if n.xattrsCache != nil { - n.xattrsCache[key] = []byte(val) - } - - return n.lu.MetadataBackend().Set(ctx, n.InternalPath(), key, []byte(val)) -} - -// ResetXattrsCache clears the in-process xattr cache so the next read fetches from disk. -func (n *Node) ResetXattrsCache() { - n.xattrsCache = nil -} - -// RemoveXattr removes an extended attribute from the write-through cache/node -func (n *Node) RemoveXattr(ctx context.Context, key string, acquireLock bool) error { - if n.xattrsCache != nil { - delete(n.xattrsCache, key) - } - return n.lu.MetadataBackend().Remove(ctx, n.InternalPath(), key, acquireLock) -} - -// XattrsWithReader returns the extended attributes of the node. If the attributes have already -// been cached they are not read from disk again. -func (n *Node) XattrsWithReader(ctx context.Context, r io.Reader) (Attributes, error) { - if n.ID == "" { - // Do not try to read the attribute of an empty node. The InternalPath points to the - // base nodes directory in this case. - return Attributes{}, &xattr.Error{Op: "node.XattrsWithReader", Path: n.InternalPath(), Err: xattr.ENOATTR} - } - - if n.xattrsCache != nil { - return n.xattrsCache, nil - } - - var attrs Attributes - var err error - if r != nil { - attrs, err = n.lu.MetadataBackend().AllWithLockedSource(ctx, n.InternalPath(), r) - } else { - attrs, err = n.lu.MetadataBackend().All(ctx, n.InternalPath()) - } - if err != nil { - return nil, err - } - - n.xattrsCache = attrs - return n.xattrsCache, nil -} - -// Xattrs returns the extended attributes of the node. If the attributes have already -// been cached they are not read from disk again. -func (n *Node) Xattrs(ctx context.Context) (Attributes, error) { - return n.XattrsWithReader(ctx, nil) -} - -// Xattr returns an extended attribute of the node. If the attributes have already -// been cached it is not read from disk again. -func (n *Node) Xattr(ctx context.Context, key string) ([]byte, error) { - path := n.InternalPath() - - if path == "" { - // Do not try to read the attribute of an non-existing node - return []byte{}, fs.ErrNotExist - } - - if n.ID == "" { - // Do not try to read the attribute of an empty node. The InternalPath points to the - // base nodes directory in this case. - return []byte{}, &xattr.Error{Op: "node.Xattr", Path: path, Name: key, Err: xattr.ENOATTR} - } - - if n.xattrsCache == nil { - attrs, err := n.lu.MetadataBackend().All(ctx, path) - if err != nil { - return []byte{}, err - } - n.xattrsCache = attrs - } - - if val, ok := n.xattrsCache[key]; ok { - return val, nil - } - // wrap the error as xattr does - return []byte{}, &xattr.Error{Op: "node.Xattr", Path: path, Name: key, Err: xattr.ENOATTR} -} - -// XattrString returns the string representation of an attribute -func (n *Node) XattrString(ctx context.Context, key string) (string, error) { - b, err := n.Xattr(ctx, key) - if err != nil { - return "", err - } - return string(b), nil -} - -// XattrInt32 returns the int32 representation of an attribute -func (n *Node) XattrInt32(ctx context.Context, key string) (int32, error) { - b, err := n.XattrString(ctx, key) - if err != nil { - return 0, err - } - - typeInt, err := strconv.ParseInt(b, 10, 32) - if err != nil { - return 0, err - } - return int32(typeInt), nil -} - -// XattrInt64 returns the int64 representation of an attribute -func (n *Node) XattrInt64(ctx context.Context, key string) (int64, error) { - b, err := n.XattrString(ctx, key) - if err != nil { - return 0, err - } - return strconv.ParseInt(b, 10, 64) -} - -// XattrUint64 returns the uint64 representation of an attribute -func (n *Node) XattrUint64(ctx context.Context, key string) (uint64, error) { - b, err := n.XattrString(ctx, key) - if err != nil { - return 0, err - } - return strconv.ParseUint(b, 10, 64) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options/options.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options/options.go deleted file mode 100644 index d32a929550..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options/options.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package options - -import ( - "path/filepath" - "strings" - "time" - - "github.com/go-viper/mapstructure/v2" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" - "github.com/opencloud-eu/reva/v2/pkg/sharedconf" - "github.com/opencloud-eu/reva/v2/pkg/storage/cache" - "github.com/pkg/errors" -) - -// Option defines a single option function. -type Option func(o *Options) - -// Options defines the available options for this package. -type Options struct { - - // the gateway address - GatewayAddr string `mapstructure:"gateway_addr"` - - // the metadata backend to use, currently supports `xattr` or `ini` - MetadataBackend string `mapstructure:"metadata_backend"` - - // the propagator to use for this fs. currently only `sync` is fully supported, `async` is available as an experimental feature - Propagator string `mapstructure:"propagator"` - // Options specific to the async propagator - AsyncPropagatorOptions AsyncPropagatorOptions `mapstructure:"async_propagator_options"` - - // ocis fs works on top of a dir of uuid nodes - Root string `mapstructure:"root"` - - // the upload directory where uploads in progress are stored - UploadDirectory string `mapstructure:"upload_directory"` - - // UserLayout describes the relative path from the storage's root node to the users home node. - UserLayout string `mapstructure:"user_layout"` - - // ProjectLayout describes the relative path from the storage's root node to the project spaces root directory. - ProjectLayout string `mapstructure:"project_layout"` - - // propagate mtime changes as tmtime (tree modification time) to the parent directory when user.ocis.propagation=1 is set on a node - TreeTimeAccounting bool `mapstructure:"treetime_accounting"` - - // propagate size changes as treesize - TreeSizeAccounting bool `mapstructure:"treesize_accounting"` - - // permissions service to use when checking permissions - PermissionsSVC string `mapstructure:"permissionssvc"` - PermissionsClientTLSMode string `mapstructure:"permissionssvc_tls_mode"` - PermTLSMode pool.TLSMode - - PersonalSpaceAliasTemplate string `mapstructure:"personalspacealias_template"` - PersonalSpacePathTemplate string `mapstructure:"personalspacepath_template"` - GeneralSpaceAliasTemplate string `mapstructure:"generalspacealias_template"` - GeneralSpacePathTemplate string `mapstructure:"generalspacepath_template"` - - AsyncFileUploads bool `mapstructure:"asyncfileuploads"` - - Events EventOptions `mapstructure:"events"` - - Tokens TokenOptions `mapstructure:"tokens"` - - StatCache cache.Config `mapstructure:"statcache"` - FileMetadataCache cache.Config `mapstructure:"filemetadatacache"` - IDCache cache.Config `mapstructure:"idcache"` - - MaxAcquireLockCycles int `mapstructure:"max_acquire_lock_cycles"` - LockCycleDurationFactor int `mapstructure:"lock_cycle_duration_factor"` - MaxConcurrency int `mapstructure:"max_concurrency"` - - MaxQuota uint64 `mapstructure:"max_quota"` - - DisableVersioning bool `mapstructure:"disable_versioning"` - - MountID string `mapstructure:"mount_id"` -} - -// AsyncPropagatorOptions holds the configuration for the async propagator -type AsyncPropagatorOptions struct { - PropagationDelay time.Duration `mapstructure:"propagation_delay"` -} - -// EventOptions are the configurable options for events -type EventOptions struct { - NumConsumers int `mapstructure:"numconsumers"` -} - -// TokenOptions are the configurable option for tokens -type TokenOptions struct { - DownloadEndpoint string `mapstructure:"download_endpoint"` - DataGatewayEndpoint string `mapstructure:"datagateway_endpoint"` - TransferSharedSecret string `mapstructure:"transfer_shared_secret"` - TransferExpires int64 `mapstructure:"transfer_expires"` -} - -// New returns a new Options instance for the given configuration -func New(m map[string]interface{}) (*Options, error) { - o := &Options{} - if err := mapstructure.Decode(m, o); err != nil { - err = errors.Wrap(err, "error decoding conf") - return nil, err - } - - o.GatewayAddr = sharedconf.GetGatewaySVC(o.GatewayAddr) - - if o.MetadataBackend == "" { - o.MetadataBackend = "xattrs" - } - - // ensure user layout has no starting or trailing / - o.UserLayout = strings.Trim(o.UserLayout, "/") - - // c.DataDirectory should never end in / unless it is the root - o.Root = filepath.Clean(o.Root) - - if o.PersonalSpaceAliasTemplate == "" { - o.PersonalSpaceAliasTemplate = "{{.SpaceType}}/{{.User.Username}}" - } - - if o.GeneralSpaceAliasTemplate == "" { - o.GeneralSpaceAliasTemplate = "{{.SpaceType}}/{{.SpaceName | replace \" \" \"-\" | lower}}" - } - - if o.PermissionsClientTLSMode != "" { - var err error - o.PermTLSMode, err = pool.StringToTLSMode(o.PermissionsClientTLSMode) - if err != nil { - return nil, err - } - } else { - sharedOpt := sharedconf.GRPCClientOptions() - var err error - - if o.PermTLSMode, err = pool.StringToTLSMode(sharedOpt.TLSMode); err != nil { - return nil, err - } - } - - if o.MaxConcurrency <= 0 { - o.MaxConcurrency = 5 - } - - if o.Propagator == "" { - o.Propagator = "sync" - } - if o.AsyncPropagatorOptions.PropagationDelay == 0 { - o.AsyncPropagatorOptions.PropagationDelay = 5 * time.Second - } - - if o.UploadDirectory == "" { - o.UploadDirectory = filepath.Join(o.Root, "uploads") - } - - return o, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions/spacepermissions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions/spacepermissions.go deleted file mode 100644 index bf44405337..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions/spacepermissions.go +++ /dev/null @@ -1,169 +0,0 @@ -package permissions - -import ( - "context" - - userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - cs3permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1" - v1beta11 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" - "google.golang.org/grpc" -) - -var ( - tracer trace.Tracer -) - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/permissions") -} - -const ( - _spaceTypePersonal = "personal" - _spaceTypeProject = "project" -) - -// PermissionsChecker defines an interface for checking permissions on a Node -type PermissionsChecker interface { - AssemblePermissions(ctx context.Context, n *node.Node) (ap *provider.ResourcePermissions, err error) - AssembleTrashPermissions(ctx context.Context, n *node.Node) (ap *provider.ResourcePermissions, err error) -} - -// CS3PermissionsClient defines an interface for checking permissions against the CS3 permissions service -type CS3PermissionsClient interface { - CheckPermission(ctx context.Context, in *cs3permissions.CheckPermissionRequest, opts ...grpc.CallOption) (*cs3permissions.CheckPermissionResponse, error) -} - -// Permissions manages permissions -type Permissions struct { - item PermissionsChecker // handles item permissions - permissionsSelector pool.Selectable[cs3permissions.PermissionsAPIClient] // handlers space permissions -} - -// NewPermissions returns a new Permissions instance -func NewPermissions(item PermissionsChecker, permissionsSelector pool.Selectable[cs3permissions.PermissionsAPIClient]) Permissions { - return Permissions{item: item, permissionsSelector: permissionsSelector} -} - -// AssemblePermissions is used to assemble file permissions -func (p Permissions) AssemblePermissions(ctx context.Context, n *node.Node) (*provider.ResourcePermissions, error) { - ctx, span := tracer.Start(ctx, "AssemblePermissions") - defer span.End() - return p.item.AssemblePermissions(ctx, n) -} - -// AssembleTrashPermissions is used to assemble file permissions -func (p Permissions) AssembleTrashPermissions(ctx context.Context, n *node.Node) (*provider.ResourcePermissions, error) { - _, span := tracer.Start(ctx, "AssembleTrashPermissions") - defer span.End() - return p.item.AssembleTrashPermissions(ctx, n) -} - -// CreateSpace returns true when the user is allowed to create the space -func (p Permissions) CreateSpace(ctx context.Context, spaceid string) bool { - return p.checkPermission(ctx, "Drives.Create", spaceRef(spaceid)) -} - -// SetSpaceQuota returns true when the user is allowed to change the spaces quota -func (p Permissions) SetSpaceQuota(ctx context.Context, spaceid string, spaceType string) bool { - switch spaceType { - default: - return false // only quotas of personal and project space may be changed - case _spaceTypePersonal: - return p.checkPermission(ctx, "Drives.ReadWritePersonalQuota", spaceRef(spaceid)) - case _spaceTypeProject: - return p.checkPermission(ctx, "Drives.ReadWriteProjectQuota", spaceRef(spaceid)) - } -} - -// ManageSpaceProperties returns true when the user is allowed to change space properties (name/subtitle) -func (p Permissions) ManageSpaceProperties(ctx context.Context, spaceid string) bool { - return p.checkPermission(ctx, "Drives.ReadWrite", spaceRef(spaceid)) -} - -// SpaceAbility returns true when the user is allowed to enable/disable the space -func (p Permissions) SpaceAbility(ctx context.Context, spaceid string) bool { - return p.checkPermission(ctx, "Drives.ReadWriteEnabled", spaceRef(spaceid)) -} - -// ListAllSpaces returns true when the user is allowed to list all spaces -func (p Permissions) ListAllSpaces(ctx context.Context) bool { - return p.checkPermission(ctx, "Drives.List", nil) -} - -// ListSpacesOfUser returns true when the user is allowed to list the spaces of the given user -func (p Permissions) ListSpacesOfUser(ctx context.Context, userid *userv1beta1.UserId) bool { - switch { - case userid == nil: - // there is no filter - return true // TODO: is `true` actually correct here? Shouldn't we check for ListAllSpaces too? - case utils.UserIDEqual(ctxpkg.ContextMustGetUser(ctx).GetId(), userid): - return true - default: - return p.ListAllSpaces(ctx) - } -} - -// DeleteAllSpaces returns true when the user is allowed to delete all spaces -func (p Permissions) DeleteAllSpaces(ctx context.Context) bool { - return p.checkPermission(ctx, "Drives.DeleteProject", nil) -} - -// DeleteAllHomeSpaces returns true when the user is allowed to delete all home spaces -func (p Permissions) DeleteAllHomeSpaces(ctx context.Context) bool { - return p.checkPermission(ctx, "Drives.DeletePersonal", nil) -} - -// checkPermission is used to check a users space permissions -func (p Permissions) checkPermission(ctx context.Context, perm string, ref *provider.Reference) bool { - permissionsClient, err := p.permissionsSelector.Next() - if err != nil { - return false - } - - user := ctxpkg.ContextMustGetUser(ctx) - checkRes, err := permissionsClient.CheckPermission(ctx, &cs3permissions.CheckPermissionRequest{ - Permission: perm, - SubjectRef: &cs3permissions.SubjectReference{ - Spec: &cs3permissions.SubjectReference_UserId{ - UserId: user.Id, - }, - }, - Ref: ref, - }) - if err != nil { - return false - } - - return checkRes.Status.Code == v1beta11.Code_CODE_OK -} - -// IsManager returns true if the given resource permissions evaluate the user as "manager" -func IsManager(rp *provider.ResourcePermissions) bool { - return rp.RemoveGrant -} - -// IsEditor returns true if the given resource permissions evaluate the user as "editor" -func IsEditor(rp *provider.ResourcePermissions) bool { - return rp.InitiateFileUpload -} - -// IsViewer returns true if the given resource permissions evaluate the user as "viewer" -func IsViewer(rp *provider.ResourcePermissions) bool { - return rp.Stat -} - -func spaceRef(spaceid string) *provider.Reference { - return &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: spaceid, - // OpaqueId is the same, no need to transfer it - }, - } -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/recycle.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/recycle.go deleted file mode 100644 index 43a17474fe..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/recycle.go +++ /dev/null @@ -1,460 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - iofs "io/fs" - "os" - "path/filepath" - "strings" - "time" - - "github.com/pkg/errors" - "golang.org/x/sync/errgroup" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" -) - -type DecomposedfsTrashbin struct { - fs *Decomposedfs -} - -// Setup the trashbin -func (tb *DecomposedfsTrashbin) Setup(fs storage.FS) error { - if _, ok := fs.(*Decomposedfs); !ok { - return errors.New("invalid filesystem") - } - tb.fs = fs.(*Decomposedfs) - return nil -} - -// Recycle items are stored inside the node folder and start with the uuid of the deleted node. -// The `.T.` indicates it is a trash item and what follows is the timestamp of the deletion. -// The deleted file is kept in the same location/dir as the original node. This prevents deletes -// from triggering cross storage moves when the trash is accidentally stored on another partition, -// because the admin mounted a different partition there. -// For an efficient listing of deleted nodes the ocis storage driver maintains a 'trash' folder -// with symlinks to trash files for every storagespace. - -// ListRecycle returns the list of available recycle items -// ref -> the space (= resourceid), key -> deleted node id, relativePath = relative to key -func (tb *DecomposedfsTrashbin) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) { - _, span := tracer.Start(ctx, "ListRecycle") - defer span.End() - if ref == nil || ref.ResourceId == nil || ref.ResourceId.OpaqueId == "" { - return nil, errtypes.BadRequest("spaceid required") - } - if key == "" && relativePath != "" { - return nil, errtypes.BadRequest("key is required when navigating with a path") - } - spaceID := ref.ResourceId.OpaqueId - - sublog := appctx.GetLogger(ctx).With().Str("spaceid", spaceID).Str("key", key).Str("relative_path", relativePath).Logger() - - // check permissions - trashnode, err := tb.fs.lu.NodeFromSpaceID(ctx, spaceID) - if err != nil { - return nil, err - } - rp, err := tb.fs.p.AssembleTrashPermissions(ctx, trashnode) - switch { - case err != nil: - return nil, err - case !rp.ListRecycle: - if rp.Stat { - return nil, errtypes.PermissionDenied(key) - } - return nil, errtypes.NotFound(key) - } - - if key == "" && relativePath == "" { - return tb.listTrashRoot(ctx, spaceID) - } - - // build a list of trash items relative to the given trash root and path - items := make([]*provider.RecycleItem, 0) - - trashRootPath := filepath.Join(tb.getRecycleRoot(spaceID), lookup.Pathify(key, 4, 2)) - originalPath, _, timeSuffix, err := readTrashLink(trashRootPath) - if err != nil { - sublog.Error().Err(err).Str("trashRoot", trashRootPath).Msg("error reading trash link") - return nil, err - } - - origin := "" - attrs, err := tb.fs.lu.MetadataBackend().All(ctx, originalPath) - if err != nil { - return items, err - } - // lookup origin path in extended attributes - if attrBytes, ok := attrs[prefixes.TrashOriginAttr]; ok { - origin = string(attrBytes) - } else { - sublog.Error().Err(err).Str("spaceid", spaceID).Msg("could not read origin path, skipping") - return nil, err - } - - // all deleted items have the same deletion time - var deletionTime *types.Timestamp - if parsed, err := time.Parse(time.RFC3339Nano, timeSuffix); err == nil { - deletionTime = &types.Timestamp{ - Seconds: uint64(parsed.Unix()), - // TODO nanos - } - } else { - sublog.Error().Err(err).Msg("could not parse time format, ignoring") - } - - var size int64 - if relativePath == "" { - // this is the case when we want to directly list a file in the trashbin - nodeType := tb.fs.lu.TypeFromPath(ctx, originalPath) - switch nodeType { - case provider.ResourceType_RESOURCE_TYPE_FILE: - _, size, err = tb.fs.lu.ReadBlobIDAndSizeAttr(ctx, originalPath, nil) - if err != nil { - return items, err - } - case provider.ResourceType_RESOURCE_TYPE_CONTAINER: - size, err = tb.fs.lu.MetadataBackend().GetInt64(ctx, originalPath, prefixes.TreesizeAttr) - if err != nil { - return items, err - } - } - item := &provider.RecycleItem{ - Type: tb.fs.lu.TypeFromPath(ctx, originalPath), - Size: uint64(size), - Key: filepath.Join(key, relativePath), - DeletionTime: deletionTime, - Ref: &provider.Reference{ - Path: filepath.Join(origin, relativePath), - }, - } - items = append(items, item) - return items, err - } - - // we have to read the names and stat the path to follow the symlinks - childrenPath := filepath.Join(originalPath, relativePath) - childrenDir, err := os.Open(childrenPath) - if err != nil { - return nil, err - } - - names, err := childrenDir.Readdirnames(0) - if err != nil { - return nil, err - } - for _, name := range names { - resolvedChildPath, err := filepath.EvalSymlinks(filepath.Join(childrenPath, name)) - if err != nil { - sublog.Error().Err(err).Str("name", name).Msg("could not resolve symlink, skipping") - continue - } - - // reset size - size = 0 - - nodeType := tb.fs.lu.TypeFromPath(ctx, resolvedChildPath) - switch nodeType { - case provider.ResourceType_RESOURCE_TYPE_FILE: - _, size, err = tb.fs.lu.ReadBlobIDAndSizeAttr(ctx, resolvedChildPath, nil) - if err != nil { - sublog.Error().Err(err).Str("name", name).Msg("invalid blob size, skipping") - continue - } - case provider.ResourceType_RESOURCE_TYPE_CONTAINER: - size, err = tb.fs.lu.MetadataBackend().GetInt64(ctx, resolvedChildPath, prefixes.TreesizeAttr) - if err != nil { - sublog.Error().Err(err).Str("name", name).Msg("invalid tree size, skipping") - continue - } - case provider.ResourceType_RESOURCE_TYPE_INVALID: - sublog.Error().Err(err).Str("name", name).Str("resolvedChildPath", resolvedChildPath).Msg("invalid node type, skipping") - continue - } - - item := &provider.RecycleItem{ - Type: nodeType, - Size: uint64(size), - Key: filepath.Join(key, relativePath, name), - DeletionTime: deletionTime, - Ref: &provider.Reference{ - Path: filepath.Join(origin, relativePath, name), - }, - } - items = append(items, item) - } - return items, nil -} - -// readTrashLink returns path, nodeID and timestamp -func readTrashLink(path string) (string, string, string, error) { - link, err := os.Readlink(path) - if err != nil { - return "", "", "", err - } - resolved, err := filepath.EvalSymlinks(path) - if err != nil { - return "", "", "", err - } - // ../../../../../nodes/e5/6c/75/a8/-d235-4cbb-8b4e-48b6fd0f2094.T.2022-02-16T14:38:11.769917408Z - // TODO use filepath.Separator to support windows - link = strings.ReplaceAll(link, "/", "") - // ..........nodese56c75a8-d235-4cbb-8b4e-48b6fd0f2094.T.2022-02-16T14:38:11.769917408Z - if link[0:15] != "..........nodes" || link[51:54] != node.TrashIDDelimiter { - return "", "", "", errtypes.InternalError("malformed trash link") - } - return resolved, link[15:51], link[54:], nil -} - -func (tb *DecomposedfsTrashbin) listTrashRoot(ctx context.Context, spaceID string) ([]*provider.RecycleItem, error) { - log := appctx.GetLogger(ctx) - trashRoot := tb.getRecycleRoot(spaceID) - items := []*provider.RecycleItem{} - subTrees, err := filepath.Glob(trashRoot + "/*") - if err != nil { - return nil, err - } - - numWorkers := tb.fs.o.MaxConcurrency - if len(subTrees) < numWorkers { - numWorkers = len(subTrees) - } - - work := make(chan string, len(subTrees)) - results := make(chan *provider.RecycleItem, len(subTrees)) - - g, ctx := errgroup.WithContext(ctx) - - // Distribute work - g.Go(func() error { - defer close(work) - for _, itemPath := range subTrees { - select { - case work <- itemPath: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - - // Spawn workers that'll concurrently work the queue - for i := 0; i < numWorkers; i++ { - g.Go(func() error { - for subTree := range work { - matches, err := filepath.Glob(subTree + "/*/*/*/*") - if err != nil { - return err - } - - for _, itemPath := range matches { - // TODO can we encode this in the path instead of reading the link? - nodePath, nodeID, timeSuffix, err := readTrashLink(itemPath) - if err != nil { - log.Error().Err(err).Str("trashRoot", trashRoot).Str("item", itemPath).Msg("error reading trash link, skipping") - continue - } - - md, err := os.Stat(nodePath) - if err != nil { - log.Error().Err(err).Str("trashRoot", trashRoot).Str("item", itemPath).Str("node_path", nodePath).Msg("could not stat trash item, skipping") - continue - } - - attrs, err := tb.fs.lu.MetadataBackend().All(ctx, nodePath) - if err != nil { - log.Error().Err(err).Str("trashRoot", trashRoot).Str("item", itemPath).Str("node_path", nodePath).Msg("could not get extended attributes, skipping") - continue - } - - nodeType := tb.fs.lu.TypeFromPath(ctx, nodePath) - if nodeType == provider.ResourceType_RESOURCE_TYPE_INVALID { - log.Error().Err(err).Str("trashRoot", trashRoot).Str("item", itemPath).Str("node_path", nodePath).Msg("invalid node type, skipping") - continue - } - - item := &provider.RecycleItem{ - Type: nodeType, - Size: uint64(md.Size()), - Key: nodeID, - } - if deletionTime, err := time.Parse(time.RFC3339Nano, timeSuffix); err == nil { - item.DeletionTime = &types.Timestamp{ - Seconds: uint64(deletionTime.Unix()), - // TODO nanos - } - } else { - log.Error().Err(err).Str("trashRoot", trashRoot).Str("item", itemPath).Str("spaceid", spaceID).Str("nodeid", nodeID).Str("dtime", timeSuffix).Msg("could not parse time format, ignoring") - } - - // lookup origin path in extended attributes - if attr, ok := attrs[prefixes.TrashOriginAttr]; ok { - item.Ref = &provider.Reference{Path: string(attr)} - } else { - log.Error().Str("trashRoot", trashRoot).Str("item", itemPath).Str("spaceid", spaceID).Str("nodeid", nodeID).Str("dtime", timeSuffix).Msg("could not read origin path") - } - - select { - case results <- item: - case <-ctx.Done(): - return ctx.Err() - } - } - } - return nil - }) - } - - // Wait for things to settle down, then close results chan - go func() { - _ = g.Wait() // error is checked later - close(results) - }() - - // Collect results - for ri := range results { - items = append(items, ri) - } - return items, nil -} - -// RestoreRecycleItem restores the specified item -func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error { - _, span := tracer.Start(ctx, "RestoreRecycleItem") - defer span.End() - if ref == nil { - return errtypes.BadRequest("missing reference, needs a space id") - } - - var targetNode *node.Node - if restoreRef != nil { - tn, err := tb.fs.lu.NodeFromResource(ctx, restoreRef) - if err != nil { - return err - } - - targetNode = tn - } - - rn, parent, restoreFunc, err := tb.fs.tp.RestoreRecycleItemFunc(ctx, ref.ResourceId.SpaceId, key, relativePath, targetNode) - if err != nil { - return err - } - - // check permissions of deleted node - rp, err := tb.fs.p.AssembleTrashPermissions(ctx, rn) - switch { - case err != nil: - return err - case !rp.RestoreRecycleItem: - if rp.Stat { - return errtypes.PermissionDenied(key) - } - return errtypes.NotFound(key) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, rn.SpaceOwnerOrManager(ctx)) - - // check we can write to the parent of the restore reference - pp, err := tb.fs.p.AssemblePermissions(ctx, parent) - switch { - case err != nil: - return err - case !pp.InitiateFileUpload: - // share receiver cannot restore to a shared resource to which she does not have write permissions. - if rp.Stat { - return errtypes.PermissionDenied(key) - } - return errtypes.NotFound(key) - } - - // Run the restore func - return restoreFunc() -} - -// PurgeRecycleItem purges the specified item, all its children and all their revisions -func (tb *DecomposedfsTrashbin) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error { - _, span := tracer.Start(ctx, "PurgeRecycleItem") - defer span.End() - if ref == nil { - return errtypes.BadRequest("missing reference, needs a space id") - } - - rn, purgeFunc, err := tb.fs.tp.PurgeRecycleItemFunc(ctx, ref.ResourceId.OpaqueId, key, relativePath) - if err != nil { - if errors.Is(err, iofs.ErrNotExist) { - return errtypes.NotFound(key) - } - return err - } - - // check permissions of deleted node - rp, err := tb.fs.p.AssembleTrashPermissions(ctx, rn) - switch { - case err != nil: - return err - case !rp.PurgeRecycle: - if rp.Stat { - return errtypes.PermissionDenied(key) - } - return errtypes.NotFound(key) - } - - // Run the purge func - return purgeFunc() -} - -// EmptyRecycle empties the trash -func (tb *DecomposedfsTrashbin) EmptyRecycle(ctx context.Context, ref *provider.Reference) error { - _, span := tracer.Start(ctx, "EmptyRecycle") - defer span.End() - if ref == nil || ref.ResourceId == nil || ref.ResourceId.OpaqueId == "" { - return errtypes.BadRequest("spaceid must be set") - } - - items, err := tb.ListRecycle(ctx, ref, "", "") - if err != nil { - return err - } - - for _, i := range items { - if err := tb.PurgeRecycleItem(ctx, ref, i.Key, ""); err != nil { - return err - } - } - // TODO what permission should we check? we could check the root node of the user? or the owner permissions on his home root node? - // The current impl will wipe your own trash. or when no user provided the trash of 'root' - return os.RemoveAll(tb.getRecycleRoot(ref.ResourceId.SpaceId)) -} - -func (tb *DecomposedfsTrashbin) getRecycleRoot(spaceID string) string { - return filepath.Join(tb.fs.getSpaceRoot(spaceID), "trash") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/revisions.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/revisions.go deleted file mode 100644 index 12425e0f12..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/revisions.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "io" - "os" - "path/filepath" - "strings" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -// Revision entries are stored inside the node folder and start with the same uuid as the current version. -// The `.REV.` indicates it is a revision and what follows is a timestamp, so multiple versions -// can be kept in the same location as the current file content. This prevents new fileuploads -// to trigger cross storage moves when revisions accidentally are stored on another partition, -// because the admin mounted a different partition there. -// We can add a background process to move old revisions to a slower storage -// and replace the revision file with a symbolic link in the future, if necessary. - -// ListRevisions lists the revisions of the given resource -func (fs *Decomposedfs) ListRevisions(ctx context.Context, ref *provider.Reference) (revisions []*provider.FileVersion, err error) { - _, span := tracer.Start(ctx, "ListRevisions") - defer span.End() - var n *node.Node - if n, err = fs.lu.NodeFromResource(ctx, ref); err != nil { - return - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !rp.ListFileVersions: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, errtypes.PermissionDenied(f) - } - return nil, errtypes.NotFound(f) - } - - revisions = []*provider.FileVersion{} - np := n.InternalPath() - if items, err := filepath.Glob(np + node.RevisionIDDelimiter + "*"); err == nil { - for i := range items { - if fs.lu.MetadataBackend().IsMetaFile(items[i]) || strings.HasSuffix(items[i], ".mlock") { - continue - } - - if fi, err := os.Stat(items[i]); err == nil { - parts := strings.SplitN(fi.Name(), node.RevisionIDDelimiter, 2) - if len(parts) != 2 { - appctx.GetLogger(ctx).Error().Err(err).Str("name", fi.Name()).Msg("invalid revision name, skipping") - continue - } - mtime := fi.ModTime() - rev := &provider.FileVersion{ - Key: n.ID + node.RevisionIDDelimiter + parts[1], - Mtime: uint64(mtime.Unix()), - } - _, blobSize, err := fs.lu.ReadBlobIDAndSizeAttr(ctx, items[i], nil) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("name", fi.Name()).Msg("error reading blobsize xattr, using 0") - } - rev.Size = uint64(blobSize) - etag, err := node.CalculateEtag(n.ID, mtime) - if err != nil { - return nil, errors.Wrapf(err, "error calculating etag") - } - rev.Etag = etag - revisions = append(revisions, rev) - } - } - } - // maybe we need to sort the list by key - /* - sort.Slice(revisions, func(i, j int) bool { - return revisions[i].Key > revisions[j].Key - }) - */ - - return -} - -// DownloadRevision returns a reader for the specified revision -// FIXME the CS3 api should explicitly allow initiating revision and trash download, a related issue is https://github.com/cs3org/reva/issues/1813 -func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) { - _, span := tracer.Start(ctx, "DownloadRevision") - defer span.End() - log := appctx.GetLogger(ctx) - - // verify revision key format - kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 { - log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") - return nil, nil, errtypes.NotFound(revisionKey) - } - log.Debug().Str("revisionKey", revisionKey).Msg("DownloadRevision") - - spaceID := ref.ResourceId.SpaceId - // check if the node is available and has not been deleted - n, err := node.ReadNode(ctx, fs.lu, spaceID, kp[0], false, nil, false) - if err != nil { - return nil, nil, err - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return nil, nil, err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, nil, err - case !rp.ListFileVersions || !rp.InitiateFileDownload: // TODO add explicit permission in the CS3 api? - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return nil, nil, errtypes.PermissionDenied(f) - } - return nil, nil, errtypes.NotFound(f) - } - - contentPath := fs.lu.InternalPath(spaceID, revisionKey) - - blobid, blobsize, err := fs.lu.ReadBlobIDAndSizeAttr(ctx, contentPath, nil) - if err != nil { - return nil, nil, errors.Wrapf(err, "Decomposedfs: could not read blob id and size for revision '%s' of node '%s'", kp[1], n.ID) - } - - revisionNode := node.Node{SpaceID: spaceID, BlobID: blobid, Blobsize: blobsize} // blobsize is needed for the s3ng blobstore - - ri, err := n.AsResourceInfo(ctx, rp, nil, []string{"size", "mimetype", "etag"}, true) - if err != nil { - return nil, nil, err - } - - // update resource info with revision data - mtime, err := time.Parse(time.RFC3339Nano, kp[1]) - if err != nil { - return nil, nil, errors.Wrapf(err, "Decomposedfs: could not parse mtime for revision '%s' of node '%s'", kp[1], n.ID) - } - ri.Size = uint64(blobsize) - ri.Mtime = utils.TimeToTS(mtime) - ri.Etag, err = node.CalculateEtag(n.ID, mtime) - if err != nil { - return nil, nil, errors.Wrapf(err, "error calculating etag for revision '%s' of node '%s'", kp[1], n.ID) - } - - var reader io.ReadCloser - if openReaderFunc(ri) { - reader, err = fs.tp.ReadBlob(&revisionNode) - if err != nil { - return nil, nil, errors.Wrapf(err, "Decomposedfs: could not download blob of revision '%s' for node '%s'", n.ID, revisionKey) - } - } - return ri, reader, nil -} - -// RestoreRevision restores the specified revision of the resource -func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (returnErr error) { - _, span := tracer.Start(ctx, "RestoreRevision") - defer span.End() - log := appctx.GetLogger(ctx) - - // verify revision key format - kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 { - log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") - return errtypes.NotFound(revisionKey) - } - - spaceID := ref.ResourceId.SpaceId - // check if the node is available and has not been deleted - n, err := node.ReadNode(ctx, fs.lu, spaceID, kp[0], false, nil, false) - if err != nil { - return err - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return err - } - - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return err - case !rp.RestoreFileVersion: - f, _ := storagespace.FormatReference(ref) - if rp.Stat { - return errtypes.PermissionDenied(f) - } - return errtypes.NotFound(f) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - // check lock - if err := n.CheckLock(ctx); err != nil { - return err - } - - // check processing - if n.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - - // write lock node before copying metadata - f, err := lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return err - } - defer func() { - _ = f.Close() - _ = os.Remove(fs.lu.MetadataBackend().LockfilePath(n.InternalPath())) - }() - - // move current version to new revision - nodePath := fs.lu.InternalPath(spaceID, kp[0]) - mtime, err := n.GetMTime(ctx) - if err != nil { - log.Error().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("cannot read mtime") - return err - } - - // revisions are stored alongside the actual file, so a rename can be efficient and does not cross storage / partition boundaries - newRevisionPath := fs.lu.InternalPath(spaceID, kp[0]+node.RevisionIDDelimiter+mtime.UTC().Format(time.RFC3339Nano)) - - // touch new revision - if _, err := os.Create(newRevisionPath); err != nil { - return err - } - defer func() { - if returnErr != nil { - if err := os.Remove(newRevisionPath); err != nil { - log.Error().Err(err).Str("revision", filepath.Base(newRevisionPath)).Msg("could not clean up revision node") - } - if err := fs.lu.MetadataBackend().Purge(ctx, newRevisionPath); err != nil { - log.Error().Err(err).Str("revision", filepath.Base(newRevisionPath)).Msg("could not clean up revision node") - } - } - }() - - // copy blob metadata from node to new revision node - err = fs.lu.CopyMetadataWithSourceLock(ctx, nodePath, newRevisionPath, func(attributeName string, value []byte) (newValue []byte, copy bool) { - return value, strings.HasPrefix(attributeName, prefixes.ChecksumPrefix) || // for checksums - attributeName == prefixes.TypeAttr || - attributeName == prefixes.BlobIDAttr || - attributeName == prefixes.BlobsizeAttr || - attributeName == prefixes.MTimeAttr // FIXME somewhere I mix up the revision time and the mtime, causing the restore to overwrite the other existing revisien - }, f, true) - if err != nil { - return errtypes.InternalError("failed to copy blob xattrs to version node: " + err.Error()) - } - - // remember mtime from node as new revision mtime - if err = os.Chtimes(newRevisionPath, mtime, mtime); err != nil { - return errtypes.InternalError("failed to change mtime of version node") - } - - // update blob id in node - - // copy blob metadata from restored revision to node - restoredRevisionPath := fs.lu.InternalPath(spaceID, revisionKey) - err = fs.lu.CopyMetadata(ctx, restoredRevisionPath, nodePath, func(attributeName string, value []byte) (newValue []byte, copy bool) { - return value, strings.HasPrefix(attributeName, prefixes.ChecksumPrefix) || - attributeName == prefixes.TypeAttr || - attributeName == prefixes.BlobIDAttr || - attributeName == prefixes.BlobsizeAttr - }, false) - if err != nil { - return errtypes.InternalError("failed to copy blob xattrs to old revision to node: " + err.Error()) - } - // always set the node mtime to the current time - err = fs.lu.MetadataBackend().SetMultiple(ctx, nodePath, - map[string][]byte{ - prefixes.MTimeAttr: []byte(time.Now().UTC().Format(time.RFC3339Nano)), - }, - false) - if err != nil { - return errtypes.InternalError("failed to set mtime attribute on node: " + err.Error()) - } - - revisionSize, err := fs.lu.MetadataBackend().GetInt64(ctx, restoredRevisionPath, prefixes.BlobsizeAttr) - if err != nil { - return errtypes.InternalError("failed to read blob size xattr from old revision") - } - - // drop old revision - if err := os.Remove(restoredRevisionPath); err != nil { - log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not delete old revision, continuing") - } - if err := os.Remove(fs.lu.MetadataBackend().MetadataPath(restoredRevisionPath)); err != nil { - log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not delete old revision metadata, continuing") - } - if err := os.Remove(fs.lu.MetadataBackend().LockfilePath(restoredRevisionPath)); err != nil { - log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not delete old revision metadata lockfile, continuing") - } - if err := fs.lu.MetadataBackend().Purge(ctx, restoredRevisionPath); err != nil { - log.Warn().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("could not purge old revision from cache, continuing") - } - - // revision 5, current 10 (restore a smaller blob) -> 5-10 = -5 - // revision 10, current 5 (restore a bigger blob) -> 10-5 = +5 - sizeDiff := revisionSize - n.Blobsize - - return fs.tp.Propagate(ctx, n, sizeDiff) -} - -// DeleteRevision deletes the specified revision of the resource -func (fs *Decomposedfs) DeleteRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error { - _, span := tracer.Start(ctx, "DeleteRevision") - defer span.End() - n, err := fs.getRevisionNode(ctx, ref, revisionKey, func(rp *provider.ResourcePermissions) bool { - return rp.RestoreFileVersion - }) - if err != nil { - return err - } - - return fs.deleteRevisionFile(ctx, n, revisionKey) -} - -// deleteRevisionFile deletes the revision node identified by revisionKey -// (nodeID + RevisionIDDelimiter + timestamp) together with its metadata -// sidecars and its own blob. It is a no-op if the revision does not exist. -func (fs *Decomposedfs) deleteRevisionFile(ctx context.Context, n *node.Node, revisionKey string) error { - kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 { - return errtypes.NotFound(revisionKey) - } - - blobID, err := n.DeleteRevision(ctx, kp[1]) - if err != nil { - return err - } - if blobID == "" { - // no blob to delete (0-byte file or current-revision revert) - return nil - } - - return fs.tp.DeleteBlob(&node.Node{SpaceID: n.SpaceID, BlobID: blobID}) -} - -func (fs *Decomposedfs) getRevisionNode(ctx context.Context, ref *provider.Reference, revisionKey string, hasPermission func(*provider.ResourcePermissions) bool) (*node.Node, error) { - _, span := tracer.Start(ctx, "getRevisionNode") - defer span.End() - log := appctx.GetLogger(ctx) - - // verify revision key format - kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2) - if len(kp) != 2 { - log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey") - return nil, errtypes.NotFound(revisionKey) - } - log.Debug().Str("revisionKey", revisionKey).Msg("DownloadRevision") - - spaceID := ref.ResourceId.SpaceId - // check if the node is available and has not been deleted - n, err := node.ReadNode(ctx, fs.lu, spaceID, kp[0], false, nil, false) - if err != nil { - return nil, err - } - if !n.Exists { - err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name)) - return nil, err - } - - p, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !hasPermission(p): - return nil, errtypes.PermissionDenied(filepath.Join(n.ParentID, n.Name)) - } - - // Set space owner in context - storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx)) - - return n, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex/spaceidindex.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex/spaceidindex.go deleted file mode 100644 index 14ec16a32f..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex/spaceidindex.go +++ /dev/null @@ -1,159 +0,0 @@ -package spaceidindex - -import ( - "io" - "os" - "path/filepath" - "time" - - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/shamaton/msgpack/v2" -) - -// Index holds space id indexes -type Index struct { - root string - name string - cache mtimesyncedcache.Cache[string, map[string]string] -} - -type readWriteCloseSeekTruncater interface { - io.ReadWriteCloser - io.Seeker - Truncate(int64) error -} - -// New returns a new index instance -func New(root, name string) *Index { - return &Index{ - root: root, - name: name, - } -} - -// Init initializes the index and makes sure it can be used -func (i *Index) Init() error { - // Make sure to work on an existing tree - return os.MkdirAll(filepath.Join(i.root, i.name), 0700) -} - -// Load returns the content of an index -func (i *Index) Load(index string) (map[string]string, error) { - indexPath := filepath.Join(i.root, i.name, index+".mpk") - fi, err := os.Stat(indexPath) - if err != nil { - return nil, err - } - return i.readSpaceIndex(indexPath, i.name+":"+index, fi.ModTime()) -} - -// Add adds an entry to an index -// Consider calling AddAll() when trying to add multiple entries as every Add call has to lock the index -func (i *Index) Add(index, key string, value string) error { - return i.updateIndex(index, map[string]string{key: value}, []string{}) -} - -// AddAll adds multiple entries to the index -func (i *Index) AddAll(index string, m map[string]string) error { - return i.updateIndex(index, m, []string{}) -} - -// Remove removes an entry from the index -func (i *Index) Remove(index, key string) error { - return i.updateIndex(index, map[string]string{}, []string{key}) -} - -func (i *Index) updateIndex(index string, addLinks map[string]string, removeLinks []string) error { - indexPath := filepath.Join(i.root, i.name, index+".mpk") - - var err error - // acquire writelock - var f readWriteCloseSeekTruncater - f, err = lockedfile.OpenFile(indexPath, os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return errors.Wrap(err, "unable to lock index to write") - } - defer func() { - rerr := f.Close() - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - // Read current state - msgBytes, err := io.ReadAll(f) - if err != nil { - return err - } - links := map[string]string{} - if len(msgBytes) > 0 { - err = msgpack.Unmarshal(msgBytes, &links) - if err != nil { - return err - } - } - - // set new metadata - for key, val := range addLinks { - links[key] = val - } - for _, key := range removeLinks { - delete(links, key) - } - // Truncate file - _, err = f.Seek(0, io.SeekStart) - if err != nil { - return err - } - err = f.Truncate(0) - if err != nil { - return err - } - - // Write new metadata to file - d, err := msgpack.Marshal(links) - if err != nil { - return errors.Wrap(err, "unable to marshal index") - } - _, err = f.Write(d) - if err != nil { - return errors.Wrap(err, "unable to write index") - } - return nil -} - -func (i *Index) readSpaceIndex(indexPath, cacheKey string, mtime time.Time) (map[string]string, error) { - return i.cache.LoadOrStore(cacheKey, mtime, func() (map[string]string, error) { - // Acquire a read log on the index file - f, err := lockedfile.Open(indexPath) - if err != nil { - return nil, errors.Wrap(err, "unable to lock index to read") - } - defer func() { - rerr := f.Close() - - // if err is non nil we do not overwrite that - if err == nil { - err = rerr - } - }() - - // Read current state - msgBytes, err := io.ReadAll(f) - if err != nil { - return nil, errors.Wrap(err, "unable to read index") - } - links := map[string]string{} - if len(msgBytes) > 0 { - err = msgpack.Unmarshal(msgBytes, &links) - if err != nil { - return nil, errors.Wrap(err, "unable to parse index") - } - } - return links, nil - }) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaces.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaces.go deleted file mode 100644 index ad40ab37af..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaces.go +++ /dev/null @@ -1,1141 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "encoding/json" - "fmt" - "math" - "os" - "path/filepath" - "strconv" - "strings" - "sync/atomic" - "time" - - userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - v1beta11 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/opencloud-eu/reva/v2/internal/grpc/services/storageprovider" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ocsconv "github.com/opencloud-eu/reva/v2/pkg/conversions" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/status" - "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" - sdk "github.com/opencloud-eu/reva/v2/pkg/sdk/common" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/templates" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" - "github.com/shamaton/msgpack/v2" - "golang.org/x/sync/errgroup" -) - -const ( - _spaceTypePersonal = "personal" - _spaceTypeProject = "project" - spaceTypeShare = "share" - spaceTypeAny = "*" - spaceIDAny = "*" - - quotaUnrestricted = 0 -) - -// CreateStorageSpace creates a storage space -func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { - ctx = storageprovider.WithSpaceType(ctx, "") - u := ctxpkg.ContextMustGetUser(ctx) - - // "everything is a resource" this is the unique ID for the Space resource. - spaceID, err := fs.lu.GenerateSpaceID(req.Type, req.GetOwner()) - if err != nil { - return nil, err - } - if reqSpaceID := utils.ReadPlainFromOpaque(req.Opaque, "spaceid"); reqSpaceID != "" { - spaceID = reqSpaceID - } - - // Check if space already exists - rootPath := "" - switch req.Type { - case _spaceTypePersonal: - if fs.o.PersonalSpacePathTemplate != "" { - rootPath = filepath.Join(fs.o.Root, templates.WithUser(u, fs.o.PersonalSpacePathTemplate)) - } - default: - if fs.o.GeneralSpacePathTemplate != "" { - rootPath = filepath.Join(fs.o.Root, templates.WithSpacePropertiesAndUser(u, req.Type, req.Name, spaceID, fs.o.GeneralSpacePathTemplate)) - } - } - if rootPath != "" { - if _, err := os.Stat(rootPath); err == nil { - return nil, errtypes.AlreadyExists("decomposedfs: spaces: space already exists") - } - } - - description := utils.ReadPlainFromOpaque(req.Opaque, "description") - alias := utils.ReadPlainFromOpaque(req.Opaque, "spaceAlias") - if alias == "" { - alias = templates.WithSpacePropertiesAndUser(u, req.Type, req.Name, spaceID, fs.o.GeneralSpaceAliasTemplate) - } - if req.Type == _spaceTypePersonal { - alias = templates.WithSpacePropertiesAndUser(u, req.Type, req.Name, spaceID, fs.o.PersonalSpaceAliasTemplate) - } - - root, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, true, nil, false) // will fall into `Exists` case below - switch { - case err != nil: - return nil, err - case !fs.p.CreateSpace(ctx, spaceID): - return nil, errtypes.PermissionDenied(spaceID) - case root.Exists: - return nil, errtypes.AlreadyExists("decomposedfs: spaces: space already exists") - } - - // create a directory node - root.SetType(provider.ResourceType_RESOURCE_TYPE_CONTAINER) - if rootPath == "" { - rootPath = root.InternalPath() - } - - // set 755 permissions for the base dir - if err := os.MkdirAll(filepath.Dir(rootPath), 0755); err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("Decomposedfs: error creating spaces base dir %s", filepath.Dir(rootPath))) - } - - // 770 permissions for the space - if err := os.MkdirAll(rootPath, 0770); err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("Decomposedfs: error creating space %s", rootPath)) - } - - // Store id in cache - if c, ok := fs.lu.(node.IDCacher); ok { - if err := c.CacheID(ctx, spaceID, spaceID, rootPath); err != nil { - return nil, err - } - } - - if req.GetOwner() != nil && req.GetOwner().GetId() != nil { - root.SetOwner(req.GetOwner().GetId()) - } else { - root.SetOwner(&userv1beta1.UserId{OpaqueId: spaceID, Type: userv1beta1.UserType_USER_TYPE_SPACE_OWNER}) - } - - metadata := node.Attributes{} - metadata.SetString(prefixes.IDAttr, spaceID) - metadata.SetString(prefixes.SpaceIDAttr, spaceID) - metadata.SetString(prefixes.OwnerIDAttr, root.Owner().GetOpaqueId()) - metadata.SetString(prefixes.OwnerIDPAttr, root.Owner().GetIdp()) - metadata.SetString(prefixes.OwnerTypeAttr, utils.UserTypeToString(root.Owner().GetType())) - - // always mark the space root node as the end of propagation - metadata.SetString(prefixes.PropagationAttr, "1") - metadata.SetString(prefixes.NameAttr, req.Name) - metadata.SetString(prefixes.SpaceNameAttr, req.Name) - - // This space is empty so set initial treesize to 0 - metadata.SetUInt64(prefixes.TreesizeAttr, 0) - - if req.Type != "" { - metadata.SetString(prefixes.SpaceTypeAttr, req.Type) - } - - if q := req.GetQuota(); q != nil { - // set default space quota - if fs.o.MaxQuota != quotaUnrestricted && q.GetQuotaMaxBytes() > fs.o.MaxQuota { - return nil, errtypes.BadRequest("decompsedFS: requested quota is higher than allowed") - } - metadata.SetInt64(prefixes.QuotaAttr, int64(q.QuotaMaxBytes)) - } else if fs.o.MaxQuota != quotaUnrestricted { - // If no quota was requested but a max quota was set then the the storage space has a quota - // of max quota. - metadata.SetInt64(prefixes.QuotaAttr, int64(fs.o.MaxQuota)) - } - - if description != "" { - metadata.SetString(prefixes.SpaceDescriptionAttr, description) - } - - if alias != "" { - metadata.SetString(prefixes.SpaceAliasAttr, alias) - } - - if err := root.SetXattrsWithContext(ctx, metadata, true); err != nil { - return nil, err - } - - // Write index - err = fs.updateIndexes(ctx, &provider.Grantee{ - Type: provider.GranteeType_GRANTEE_TYPE_USER, - Id: &provider.Grantee_UserId{UserId: req.GetOwner().GetId()}, - }, req.Type, root.ID, root.ID) - if err != nil { - return nil, err - } - - ctx = storageprovider.WithSpaceType(ctx, req.Type) - - if req.Type != _spaceTypePersonal { - if err := fs.AddGrant(ctx, &provider.Reference{ - ResourceId: &provider.ResourceId{ - SpaceId: spaceID, - OpaqueId: spaceID, - }, - }, &provider.Grant{ - Grantee: &provider.Grantee{ - Type: provider.GranteeType_GRANTEE_TYPE_USER, - Id: &provider.Grantee_UserId{ - UserId: u.Id, - }, - }, - Permissions: ocsconv.NewManagerRole().CS3ResourcePermissions(), - }); err != nil { - return nil, err - } - } - - space, err := fs.StorageSpaceFromNode(ctx, root, true) - if err != nil { - return nil, err - } - - resp := &provider.CreateStorageSpaceResponse{ - Status: &v1beta11.Status{ - Code: v1beta11.Code_CODE_OK, - }, - StorageSpace: space, - } - return resp, nil -} - -// ListStorageSpaces returns a list of StorageSpaces. -// The list can be filtered by space type or space id. -// Spaces are persisted with symlinks in /spaces// pointing to ../../nodes/, the root node of the space -// The spaceid is a concatenation of storageid + "!" + nodeid -func (fs *Decomposedfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) { - // TODO check filters - - // TODO when a space symlink is broken delete the space for cleanup - // read permissions are deduced from the node? - - // TODO for absolute references this actually requires us to move all user homes into a subfolder of /nodes/root, - // e.g. /nodes/root/ otherwise storage space names might collide even though they are of different types - // /nodes/root/personal/foo and /nodes/root/shares/foo might be two very different spaces, a /nodes/root/foo is not expressive enough - // we would not need /nodes/root if access always happened via spaceid+relative path - - var ( - spaceID = spaceIDAny - nodeID = spaceIDAny - requestedUserID *userv1beta1.UserId - ) - - spaceTypes := map[string]struct{}{} - - for i := range filter { - switch filter[i].Type { - case provider.ListStorageSpacesRequest_Filter_TYPE_SPACE_TYPE: - switch filter[i].GetSpaceType() { - case "+mountpoint": - // TODO include mount poits - case "+grant": - // TODO include grants - default: - spaceTypes[filter[i].GetSpaceType()] = struct{}{} - } - case provider.ListStorageSpacesRequest_Filter_TYPE_ID: - _, spaceID, nodeID, _ = storagespace.SplitID(filter[i].GetId().OpaqueId) - if strings.Contains(nodeID, "/") { - return []*provider.StorageSpace{}, nil - } - case provider.ListStorageSpacesRequest_Filter_TYPE_USER: - // TODO: refactor this to GetUserId() in cs3 - requestedUserID = filter[i].GetUser() - case provider.ListStorageSpacesRequest_Filter_TYPE_OWNER: - // TODO: improve further by not evaluating shares - requestedUserID = filter[i].GetOwner() - } - } - if len(spaceTypes) == 0 { - spaceTypes[spaceTypeAny] = struct{}{} - } - - authenticatedUserID := ctxpkg.ContextMustGetUser(ctx).GetId().GetOpaqueId() - - if !fs.p.ListSpacesOfUser(ctx, requestedUserID) { - return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s is not allowed to list spaces of other users", authenticatedUserID)) - } - - checkNodePermissions := fs.MustCheckNodePermissions(ctx, unrestricted) - - spaces := []*provider.StorageSpace{} - // build the glob path, eg. - // /path/to/root/spaces/{spaceType}/{spaceId} - // /path/to/root/spaces/personal/nodeid - // /path/to/root/spaces/shared/nodeid - - if spaceID != spaceIDAny && nodeID != spaceIDAny { - // try directly reading the node - n, err := node.ReadNode(ctx, fs.lu, spaceID, nodeID, true, nil, false) // permission to read disabled space is checked later - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("id", nodeID).Msg("could not read node") - return nil, err - } - if !n.Exists { - // return empty list - return spaces, nil - } - space, err := fs.StorageSpaceFromNode(ctx, n, checkNodePermissions) - if err != nil { - return nil, err - } - // filter space types - _, ok1 := spaceTypes[spaceTypeAny] - _, ok2 := spaceTypes[space.SpaceType] - if ok1 || ok2 { - spaces = append(spaces, space) - } - // TODO: filter user id - return spaces, nil - } - - matches := map[string]string{} - var allMatches map[string]string - var err error - - if requestedUserID != nil { - allMatches, err = fs.userSpaceIndex.Load(requestedUserID.GetOpaqueId()) - // do not return an error if the user has no spaces - if err != nil && !os.IsNotExist(err) { - return nil, errors.Wrap(err, "error reading user index") - } - - if nodeID == spaceIDAny { - for spaceID, nodeID := range allMatches { - matches[spaceID] = nodeID - } - } else { - matches[allMatches[nodeID]] = allMatches[nodeID] - } - - // get Groups for userid - user := ctxpkg.ContextMustGetUser(ctx) - // TODO the user from context may not have groups populated - if !utils.UserIDEqual(user.GetId(), requestedUserID) { - user, err = fs.UserIDToUserAndGroups(ctx, requestedUserID) - if err != nil { - return nil, err // TODO log and continue? - } - } - - for _, group := range user.Groups { - allMatches, err = fs.groupSpaceIndex.Load(group) - if err != nil { - if os.IsNotExist(err) { - continue // no spaces for this group - } - return nil, errors.Wrap(err, "error reading group index") - } - - if nodeID == spaceIDAny { - for spaceID, nodeID := range allMatches { - matches[spaceID] = nodeID - } - } else { - matches[allMatches[nodeID]] = allMatches[nodeID] - } - } - - } - - if requestedUserID == nil { - if _, ok := spaceTypes[spaceTypeAny]; ok { - // TODO do not hardcode dirs - spaceTypes = map[string]struct{}{ - "personal": {}, - "project": {}, - "share": {}, - } - } - - for spaceType := range spaceTypes { - allMatches, err = fs.spaceTypeIndex.Load(spaceType) - if err != nil { - if os.IsNotExist(err) { - continue // no spaces for this space type - } - return nil, errors.Wrap(err, "error reading type index") - } - - if nodeID == spaceIDAny { - for spaceID, nodeID := range allMatches { - matches[spaceID] = nodeID - } - } else { - matches[allMatches[nodeID]] = allMatches[nodeID] - } - } - } - - // FIXME if the space does not exist try a node as the space root. - - // But then the whole /spaces/{spaceType}/{spaceid} becomes obsolete - // we can alway just look up by nodeid - // -> no. The /spaces folder is used for efficient lookup by type, otherwise we would have - // to iterate over all nodes and read the type from extended attributes - // -> but for lookup by id we can use the node directly. - // But what about sharding nodes by space? - // an efficient lookup would be possible if we received a spaceid&opaqueid in the request - // the personal spaces must also use the nodeid and not the name - numShares := atomic.Int64{} - errg, ctx := errgroup.WithContext(ctx) - work := make(chan []string, len(matches)) - results := make(chan *provider.StorageSpace, len(matches)) - - // Distribute work - errg.Go(func() error { - defer close(work) - for spaceID, nodeID := range matches { - select { - case work <- []string{spaceID, nodeID}: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - - // Spawn workers that'll concurrently work the queue - numWorkers := 20 - if len(matches) < numWorkers { - numWorkers = len(matches) - } - for i := 0; i < numWorkers; i++ { - errg.Go(func() error { - for match := range work { - spaceID, nodeID, err := fs.tp.ResolveSpaceIDIndexEntry(match[0], match[1]) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("id", nodeID).Msg("resolve space id index entry, skipping") - continue - } - - n, err := node.ReadNode(ctx, fs.lu, spaceID, nodeID, true, nil, true) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("id", nodeID).Msg("could not read node, skipping") - continue - } - - if !n.Exists { - continue - } - - space, err := fs.StorageSpaceFromNode(ctx, n, checkNodePermissions) - if err != nil { - switch err.(type) { - case errtypes.IsPermissionDenied: - // ok - case errtypes.NotFound: - // ok - default: - appctx.GetLogger(ctx).Error().Err(err).Str("id", nodeID).Msg("could not convert to storage space") - } - continue - } - - // FIXME type share evolved to grant on the edge branch ... make it configurable if the driver should support them or not for now ... ignore type share - if space.SpaceType == spaceTypeShare { - numShares.Add(1) - // do not list shares as spaces for the owner - continue - } - - // TODO apply more filters - _, ok1 := spaceTypes[spaceTypeAny] - _, ok2 := spaceTypes[space.SpaceType] - if ok1 || ok2 { - select { - case results <- space: - case <-ctx.Done(): - return ctx.Err() - } - } - } - return nil - }) - } - - // Wait for things to settle down, then close results chan - go func() { - _ = errg.Wait() // error is checked later - close(results) - }() - - for r := range results { - r.HasTrashedItems = false // FIXME: implement me - spaces = append(spaces, r) - } - - // if there are no matches (or they happened to be spaces for the owner) and the node is a child return a space - if int64(len(matches)) <= numShares.Load() && nodeID != spaceID { - // try node id - n, err := node.ReadNode(ctx, fs.lu, spaceID, nodeID, true, nil, false) // permission to read disabled space is checked in storageSpaceFromNode - if err != nil { - return nil, err - } - if n.Exists { - space, err := fs.StorageSpaceFromNode(ctx, n, checkNodePermissions) - if err != nil { - return nil, err - } - spaces = append(spaces, space) - } - } - - return spaces, nil -} - -// UserIDToUserAndGroups converts a user ID to a user with groups -func (fs *Decomposedfs) UserIDToUserAndGroups(ctx context.Context, userid *userv1beta1.UserId) (*userv1beta1.User, error) { - user, err := fs.UserCache.Get(userid.GetOpaqueId()) - if err == nil { - return user.(*userv1beta1.User), nil - } - - gwConn, err := pool.GetGatewayServiceClient(fs.o.GatewayAddr) - if err != nil { - return nil, err - } - getUserResponse, err := gwConn.GetUser(ctx, &userv1beta1.GetUserRequest{ - UserId: userid, - SkipFetchingUserGroups: false, - }) - if err != nil { - return nil, err - } - if getUserResponse.Status.Code != v1beta11.Code_CODE_OK { - return nil, status.NewErrorFromCode(getUserResponse.Status.Code, "gateway") - } - _ = fs.UserCache.Set(userid.GetOpaqueId(), getUserResponse.GetUser()) - return getUserResponse.GetUser(), nil -} - -// MustCheckNodePermissions checks if permission checks are needed to be performed when user requests spaces -func (fs *Decomposedfs) MustCheckNodePermissions(ctx context.Context, unrestricted bool) bool { - // canListAllSpaces indicates if the user has the permission from the global user role - canListAllSpaces := fs.p.ListAllSpaces(ctx) - // unrestricted is the param which indicates if the user wants to list all spaces or only the spaces he is part of - // if a user lists all spaces unrestricted and doesn't have the permissions from the role, we need to check - // the nodePermissions and this will return a spaces list where the user has access to - // we can only skip the NodePermissions check if both values are true - if canListAllSpaces && unrestricted { - return false - } - return true -} - -// UpdateStorageSpace updates a storage space -func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { - var restore bool - if req.Opaque != nil { - _, restore = req.Opaque.Map["restore"] - } - - space := req.StorageSpace - _, spaceID, _, _ := storagespace.SplitID(space.Id.OpaqueId) - - metadata := make(node.Attributes, 5) - if space.Name != "" { - metadata.SetString(prefixes.NameAttr, space.Name) - metadata.SetString(prefixes.SpaceNameAttr, space.Name) - } - - if space.Quota != nil { - if fs.o.MaxQuota != quotaUnrestricted && fs.o.MaxQuota < space.Quota.QuotaMaxBytes { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_INVALID_ARGUMENT, Message: "decompsedFS: requested quota is higher than allowed"}, - }, nil - } else if fs.o.MaxQuota != quotaUnrestricted && space.Quota.QuotaMaxBytes == quotaUnrestricted { - // If the caller wants to unrestrict the space we give it the maximum allowed quota. - space.Quota.QuotaMaxBytes = fs.o.MaxQuota - } - metadata.SetInt64(prefixes.QuotaAttr, int64(space.Quota.QuotaMaxBytes)) - } - - // TODO also return values which are not in the request - if space.Opaque != nil { - if description, ok := space.Opaque.Map["description"]; ok { - metadata[prefixes.SpaceDescriptionAttr] = description.Value - } - if alias := utils.ReadPlainFromOpaque(space.Opaque, "spaceAlias"); alias != "" { - metadata.SetString(prefixes.SpaceAliasAttr, alias) - } - if image := utils.ReadPlainFromOpaque(space.Opaque, "image"); image != "" { - imageID, err := storagespace.ParseID(image) - if err != nil { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND, Message: "decomposedFS: space image resource not found"}, - }, nil - } - metadata.SetString(prefixes.SpaceImageAttr, imageID.OpaqueId) - } - if readme := utils.ReadPlainFromOpaque(space.Opaque, "readme"); readme != "" { - readmeID, err := storagespace.ParseID(readme) - if err != nil { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND, Message: "decomposedFS: space readme resource not found"}, - }, nil - } - metadata.SetString(prefixes.SpaceReadmeAttr, readmeID.OpaqueId) - } - } - - // check which permissions are needed - spaceNode, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, true, nil, false) - if err != nil { - return nil, err - } - - if !spaceNode.Exists { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND}, - }, nil - } - - sp, err := fs.p.AssemblePermissions(ctx, spaceNode) - if err != nil { - return &provider.UpdateStorageSpaceResponse{ - Status: status.NewStatusFromErrType(ctx, "assembling permissions failed", err), - }, nil - - } - - if !restore && len(metadata) == 0 && !permissions.IsViewer(sp) { - // you may land here when making an update request without changes - // check if user has access to the drive before continuing - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND}, - }, nil - } - - if !permissions.IsManager(sp) { - // We are not a space manager. We need to check for additional permissions. - k := []string{prefixes.NameAttr, prefixes.SpaceDescriptionAttr} - if !permissions.IsEditor(sp) { - k = append(k, prefixes.SpaceReadmeAttr, prefixes.SpaceAliasAttr, prefixes.SpaceImageAttr) - } - - if mapHasKey(metadata, k...) && !fs.p.ManageSpaceProperties(ctx, spaceID) { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_PERMISSION_DENIED}, - }, nil - } - - if restore && !fs.p.SpaceAbility(ctx, spaceID) { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_NOT_FOUND}, - }, nil - } - } - - if mapHasKey(metadata, prefixes.QuotaAttr) { - typ, err := spaceNode.SpaceRoot.Xattr(ctx, prefixes.SpaceTypeAttr) - if err != nil { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{ - Code: v1beta11.Code_CODE_INTERNAL, - Message: "space has no type", - }, - }, nil - } - - if !fs.p.SetSpaceQuota(ctx, spaceID, string(typ)) { - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_PERMISSION_DENIED}, - }, nil - } - } - metadata[prefixes.TreeMTimeAttr] = []byte(time.Now().UTC().Format(time.RFC3339Nano)) - - err = spaceNode.SetXattrsWithContext(ctx, metadata, true) - if err != nil { - return nil, err - } - - if restore { - if err := spaceNode.SetDTime(ctx, nil); err != nil { - return nil, err - } - } - - // send back the updated data from the storage - updatedSpace, err := fs.StorageSpaceFromNode(ctx, spaceNode, false) - if err != nil { - return nil, err - } - - return &provider.UpdateStorageSpaceResponse{ - Status: &v1beta11.Status{Code: v1beta11.Code_CODE_OK}, - StorageSpace: updatedSpace, - }, nil -} - -// DeleteStorageSpace deletes a storage space -func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error { - opaque := req.Opaque - var purge bool - if opaque != nil { - _, purge = opaque.Map["purge"] - } - - _, spaceID, _, err := storagespace.SplitID(req.Id.GetOpaqueId()) - if err != nil { - return err - } - - n, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, true, nil, false) // permission to read disabled space is checked later - if err != nil { - return err - } - - st, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr) - if err != nil { - return errtypes.InternalError(fmt.Sprintf("space %s does not have a spacetype, possible corrupt decompsedfs", n.ID)) - } - - if err := canDeleteSpace(ctx, spaceID, st, purge, n, fs.p); err != nil { - return err - } - if purge { - if !n.IsDisabled(ctx) { - return errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space")) - } - - // TODO invalidate ALL indexes in msgpack, not only by type - spaceType, err := n.XattrString(ctx, prefixes.SpaceTypeAttr) - if err != nil { - return err - } - if err := fs.spaceTypeIndex.Remove(spaceType, spaceID); err != nil { - return err - } - - // invalidate cache - if err := fs.lu.MetadataBackend().Purge(ctx, n.InternalPath()); err != nil { - return err - } - - root := fs.getSpaceRoot(spaceID) - - // walkfn will delete the blob if the node has one - walkfn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if filepath.Ext(path) != ".mpk" { - return nil - } - - b, err := os.ReadFile(path) - if err != nil { - return err - } - - m := map[string][]byte{} - if err := msgpack.Unmarshal(b, &m); err != nil { - return err - } - - bid := m["user.ocis.blobid"] - if string(bid) == "" { - return nil - } - - if err := fs.tp.DeleteBlob(&node.Node{ - BlobID: string(bid), - SpaceID: spaceID, - }); err != nil { - return err - } - - // remove .mpk file so subsequent attempts will not try to delete the blob again - return os.Remove(path) - } - - // This is deletes all blobs of the space - // NOTE: This isn't needed when no s3 is used, but we can't differentiate that here... - if err := filepath.Walk(root, walkfn); err != nil { - return err - } - - // remove space metadata - if err := os.RemoveAll(root); err != nil { - return err - } - - // try removing the space root node - // Note that this will fail when there are other spaceids starting with the same two digits. - _ = os.Remove(filepath.Dir(root)) - - return nil - } - - // mark as disabled by writing a dtime attribute - dtime := time.Now() - return n.SetDTime(ctx, &dtime) -} - -// the value of `target` depends on the implementation: -// - for ocis/s3ng it is the relative link to the space root -// - for the posixfs it is the node id -func (fs *Decomposedfs) updateIndexes(ctx context.Context, grantee *provider.Grantee, spaceType, spaceID, nodeID string) error { - target := fs.tp.BuildSpaceIDIndexEntry(spaceID, nodeID) - err := fs.linkStorageSpaceType(ctx, spaceType, spaceID, target) - if err != nil { - return err - } - if isShareGrant(ctx) { - // FIXME we should count the references for the by-type index currently removing the second share from the same - // space cannot determine if the by-type should be deletet, which is why we never delete them ... - return nil - } - - // create space grant index - switch grantee.Type { - case provider.GranteeType_GRANTEE_TYPE_USER: - return fs.linkSpaceByUser(ctx, grantee.GetUserId().GetOpaqueId(), spaceID, target) - case provider.GranteeType_GRANTEE_TYPE_GROUP: - return fs.linkSpaceByGroup(ctx, grantee.GetGroupId().GetOpaqueId(), spaceID, target) - default: - return errtypes.BadRequest("invalid grantee type: " + grantee.GetType().String()) - } -} - -func (fs *Decomposedfs) linkSpaceByUser(ctx context.Context, userID, spaceID, target string) error { - return fs.userSpaceIndex.Add(userID, spaceID, target) -} - -func (fs *Decomposedfs) linkSpaceByGroup(ctx context.Context, groupID, spaceID, target string) error { - return fs.groupSpaceIndex.Add(groupID, spaceID, target) -} - -func (fs *Decomposedfs) linkStorageSpaceType(ctx context.Context, spaceType, spaceID, target string) error { - return fs.spaceTypeIndex.Add(spaceType, spaceID, target) -} - -func (fs *Decomposedfs) StorageSpaceFromNode(ctx context.Context, n *node.Node, checkPermissions bool) (*provider.StorageSpace, error) { - user := ctxpkg.ContextMustGetUser(ctx) - if checkPermissions { - rp, err := fs.p.AssemblePermissions(ctx, n) - switch { - case err != nil: - return nil, err - case !rp.Stat: - return nil, errtypes.NotFound(fmt.Sprintf("space %s not found", n.ID)) - } - - if n.SpaceRoot.IsDisabled(ctx) { - rp, err := fs.p.AssemblePermissions(ctx, n) - if err != nil || !permissions.IsManager(rp) { - return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s is not allowed to list deleted spaces %s", user.Username, n.ID)) - } - } - } - - sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Logger() - - var err error - // TODO apply more filters - var sname string - if sname, err = n.SpaceRoot.XattrString(ctx, prefixes.SpaceNameAttr); err != nil { - // FIXME: Is that a severe problem? - sublog.Debug().Err(err).Msg("space does not have a name attribute") - } - - /* - if err := n.FindStorageSpaceRoot(); err != nil { - return nil, err - } - */ - - // read the grants from the current node, not the root - grants, err := n.ListGrants(ctx) - if err != nil { - return nil, err - } - - grantMap := make(map[string]*provider.ResourcePermissions, len(grants)) - grantExpiration := make(map[string]*types.Timestamp) - groupMap := make(map[string]struct{}) - for _, g := range grants { - var id string - switch g.Grantee.Type { - case provider.GranteeType_GRANTEE_TYPE_GROUP: - id = g.Grantee.GetGroupId().OpaqueId - groupMap[id] = struct{}{} - case provider.GranteeType_GRANTEE_TYPE_USER: - id = g.Grantee.GetUserId().OpaqueId - default: - continue - } - - if g.Expiration != nil { - // We are doing this check here because we want to remove expired grants "on access". - // This way we don't have to have a cron job checking the grants in regular intervals. - // The tradeof obviously is that this code is here. - if isGrantExpired(g) { - if err := n.DeleteGrant(ctx, g, true); err != nil { - sublog.Error().Err(err).Str("grantee", id). - Msg("failed to delete expired space grant") - } - if n.IsSpaceRoot(ctx) { - // invalidate space grant - switch g.Grantee.Type { - case provider.GranteeType_GRANTEE_TYPE_USER: - // remove from user index - if err := fs.userSpaceIndex.Remove(g.Grantee.GetUserId().GetOpaqueId(), n.SpaceID); err != nil { - sublog.Error().Err(err).Str("grantee", id). - Msg("failed to delete expired user space index") - } - case provider.GranteeType_GRANTEE_TYPE_GROUP: - // remove from group index - if err := fs.groupSpaceIndex.Remove(g.Grantee.GetGroupId().GetOpaqueId(), n.SpaceID); err != nil { - sublog.Error().Err(err).Str("grantee", id). - Msg("failed to delete expired group space index") - } - } - } - - continue - } - grantExpiration[id] = g.Expiration - } - grantMap[id] = g.Permissions - } - - grantMapJSON, err := json.Marshal(grantMap) - if err != nil { - return nil, err - } - - grantExpirationMapJSON, err := json.Marshal(grantExpiration) - if err != nil { - return nil, err - } - - groupMapJSON, err := json.Marshal(groupMap) - if err != nil { - return nil, err - } - - ssID, err := storagespace.FormatReference( - &provider.Reference{ - ResourceId: &provider.ResourceId{ - SpaceId: n.SpaceRoot.SpaceID, - OpaqueId: n.SpaceRoot.ID}, - }, - ) - if err != nil { - return nil, err - } - space := &provider.StorageSpace{ - Opaque: &types.Opaque{ - Map: map[string]*types.OpaqueEntry{ - "grants": { - Decoder: "json", - Value: grantMapJSON, - }, - "grants_expirations": { - Decoder: "json", - Value: grantExpirationMapJSON, - }, - "groups": { - Decoder: "json", - Value: groupMapJSON, - }, - }, - }, - Id: &provider.StorageSpaceId{OpaqueId: ssID}, - Root: &provider.ResourceId{ - SpaceId: n.SpaceRoot.SpaceID, - OpaqueId: n.SpaceRoot.ID, - }, - Name: sname, - // SpaceType is read from xattr below - // Mtime is set either as node.tmtime or as fi.mtime below - } - - space.SpaceType, err = n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr) - if err != nil { - appctx.GetLogger(ctx).Debug().Err(err).Msg("space does not have a type attribute") - } - - if n.SpaceRoot.IsDisabled(ctx) { - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "trashed", "trashed") - } - - if n.Owner() != nil && n.Owner().OpaqueId != "" { - space.Owner = &userv1beta1.User{ // FIXME only return a UserID, not a full blown user object - Id: n.Owner(), - } - } - - // we set the space mtime to the root item mtime - // override the stat mtime with a tmtime if it is present - var tmtime time.Time - if tmt, err := n.GetTMTime(ctx); err == nil { - tmtime = tmt - un := tmt.UnixNano() - space.Mtime = &types.Timestamp{ - Seconds: uint64(un / 1000000000), - Nanos: uint32(un % 1000000000), - } - } else if fi, err := os.Stat(n.InternalPath()); err == nil { - // fall back to stat mtime - tmtime = fi.ModTime() - un := fi.ModTime().UnixNano() - space.Mtime = &types.Timestamp{ - Seconds: uint64(un / 1000000000), - Nanos: uint32(un % 1000000000), - } - } - - etag, err := node.CalculateEtag(n.ID, tmtime) - if err != nil { - return nil, err - } - space.Opaque.Map["etag"] = &types.OpaqueEntry{ - Decoder: "plain", - Value: []byte(etag), - } - - spaceAttributes, err := n.SpaceRoot.Xattrs(ctx) - if err != nil { - return nil, err - } - - // if quota is set try parsing it as int64, otherwise don't bother - if q, err := spaceAttributes.Int64(prefixes.QuotaAttr); err == nil && q >= 0 { - // make sure we have a proper signed int - // we use the same magic numbers to indicate: - // -1 = uncalculated - // -2 = unknown - // -3 = unlimited - space.Quota = &provider.Quota{ - QuotaMaxBytes: uint64(q), - QuotaMaxFiles: math.MaxUint64, // TODO MaxUInt64? = unlimited? why even max files? 0 = unlimited? - } - - } - if si := spaceAttributes.String(prefixes.SpaceImageAttr); si != "" { - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "image", storagespace.FormatResourceID( - &provider.ResourceId{StorageId: space.Root.StorageId, SpaceId: space.Root.SpaceId, OpaqueId: si}, - )) - } - if sd := spaceAttributes.String(prefixes.SpaceDescriptionAttr); sd != "" { - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "description", sd) - } - if sr := spaceAttributes.String(prefixes.SpaceReadmeAttr); sr != "" { - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "readme", storagespace.FormatResourceID( - &provider.ResourceId{StorageId: space.Root.StorageId, SpaceId: space.Root.SpaceId, OpaqueId: sr}, - )) - } - if sa := spaceAttributes.String(prefixes.SpaceAliasAttr); sa != "" { - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "spaceAlias", sa) - } - - // add rootinfo - ps, _ := n.SpaceRoot.PermissionSet(ctx) - space.RootInfo, _ = n.SpaceRoot.AsResourceInfo(ctx, ps, []string{"quota"}, nil, false) - - // we cannot put free, used and remaining into the quota, as quota, when set would always imply a quota limit - // for now we use opaque properties with a 'quota.' prefix - quotaStr := node.QuotaUnknown - if quotaInOpaque := sdk.DecodeOpaqueMap(space.RootInfo.Opaque)["quota"]; quotaInOpaque != "" { - quotaStr = quotaInOpaque - } - - total, used, remaining, err := fs.calculateTotalUsedRemaining(quotaStr, space.GetRootInfo().GetSize()) - if err != nil { - return nil, err - } - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "quota.total", strconv.FormatUint(total, 10)) - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "quota.used", strconv.FormatUint(used, 10)) - space.Opaque = utils.AppendPlainToOpaque(space.Opaque, "quota.remaining", strconv.FormatUint(remaining, 10)) - - return space, nil -} - -func mapHasKey(checkMap map[string][]byte, keys ...string) bool { - for _, key := range keys { - if _, hasKey := checkMap[key]; hasKey { - return true - } - } - return false -} - -func isGrantExpired(g *provider.Grant) bool { - if g.Expiration == nil { - return false - } - return time.Now().After(time.Unix(int64(g.Expiration.Seconds), int64(g.Expiration.Nanos))) -} - -func (fs *Decomposedfs) getSpaceRoot(spaceID string) string { - return filepath.Join(fs.o.Root, "spaces", lookup.Pathify(spaceID, 1, 2)) -} - -// Space deletion can be tricky as there are lots of different cases: -// - spaces of type personal can only be disabled and deleted by users with the "delete-all-home-spaces" permission -// - a user with the "delete-all-spaces" permission may delete but not enable/disable any project space -// - a user with the "Drive.ReadWriteEnabled" permission may enable/disable but not delete any project space -// - a project space can always be enabled/disabled/deleted by its manager (i.e. users have the "remove" grant) -func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool, n *node.Node, p permissions.Permissions) error { - // delete-all-home spaces allows to disable and delete a personal space - if typ == "personal" { - if p.DeleteAllHomeSpaces(ctx) { - return nil - } - return errtypes.PermissionDenied("user is not allowed to delete a personal space") - } - - // space managers are allowed to disable and delete their project spaces - if rp, err := p.AssemblePermissions(ctx, n); err == nil && permissions.IsManager(rp) { - return nil - } - - // delete-all-spaces permissions allows to delete (purge, NOT disable) project spaces - if purge && p.DeleteAllSpaces(ctx) { - return nil - } - - // Drive.ReadWriteEnabled allows to disable a space - if !purge && p.SpaceAbility(ctx, spaceID) { - return nil - } - - return errtypes.PermissionDenied(fmt.Sprintf("user is not allowed to delete space %s", n.ID)) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager/timemanager.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager/timemanager.go deleted file mode 100644 index b478499cce..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager/timemanager.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2018-2024 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. -package timemanager - -import ( - "context" - "os" - "time" - - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" -) - -// Manager is responsible for managing time-related attributes of nodes in a decomposed file system. -type Manager struct { -} - -// OverrideMtime overrides the modification time (mtime) attribute of a node with the given time. -func (m *Manager) OverrideMtime(ctx context.Context, _ *node.Node, attrs *node.Attributes, mtime time.Time) error { - attrs.SetString(prefixes.MTimeAttr, mtime.UTC().Format(time.RFC3339Nano)) - return nil -} - -// MTime retrieves the modification time (mtime) attribute of a node. -// If the attribute is not set, it falls back to the file's last modification time. -func (dtm *Manager) MTime(ctx context.Context, n *node.Node) (time.Time, error) { - b, err := n.XattrString(ctx, prefixes.MTimeAttr) - if err != nil { - fi, err := os.Lstat(n.InternalPath()) - if err != nil { - return time.Time{}, err - } - return fi.ModTime(), nil - } - return time.Parse(time.RFC3339Nano, b) -} - -// SetMTime sets the modification time (mtime) attribute of a node to the given time. -// If the time is nil, the attribute is removed. -func (dtm *Manager) SetMTime(ctx context.Context, n *node.Node, mtime *time.Time) error { - if mtime == nil { - return n.RemoveXattr(ctx, prefixes.MTimeAttr, true) - } - return n.SetXattrString(ctx, prefixes.MTimeAttr, mtime.UTC().Format(time.RFC3339Nano)) -} - -// TMTime retrieves the tree modification time (tmtime) attribute of a node. -// If the attribute is not set, it falls back to the node's modification time (mtime). -func (dtm *Manager) TMTime(ctx context.Context, n *node.Node) (time.Time, error) { - b, err := n.XattrString(ctx, prefixes.TreeMTimeAttr) - if err == nil { - return time.Parse(time.RFC3339Nano, b) - } - - // no tmtime, use mtime - return dtm.MTime(ctx, n) -} - -// SetTMTime sets the tree modification time (tmtime) attribute of a node to the given time. -// If the time is nil, the attribute is removed. -func (dtm *Manager) SetTMTime(ctx context.Context, n *node.Node, tmtime *time.Time) error { - if tmtime == nil { - return n.RemoveXattr(ctx, prefixes.TreeMTimeAttr, true) - } - return n.SetXattrString(ctx, prefixes.TreeMTimeAttr, tmtime.UTC().Format(time.RFC3339Nano)) -} - -// CTime retrieves the creation time (ctime) attribute of a node. -// Since decomposedfs does not differentiate between ctime and mtime, it falls back to the node's modification time (mtime). -func (dtm *Manager) CTime(ctx context.Context, n *node.Node) (time.Time, error) { - // decomposedfs does not differentiate between ctime and mtime - return dtm.MTime(ctx, n) -} - -// SetCTime sets the creation time (ctime) attribute of a node to the given time. -// Since decomposedfs does not differentiate between ctime and mtime, it sets the modification time (mtime) instead. -func (dtm *Manager) SetCTime(ctx context.Context, n *node.Node, mtime *time.Time) error { - // decomposedfs does not differentiate between ctime and mtime - return dtm.SetMTime(ctx, n, mtime) -} - -// TCTime retrieves the tree creation time (tctime) attribute of a node. -// Since decomposedfs does not differentiate between ctime and mtime, it falls back to the tree modification time (tmtime). -func (dtm *Manager) TCTime(ctx context.Context, n *node.Node) (time.Time, error) { - // decomposedfs does not differentiate between ctime and mtime - return dtm.TMTime(ctx, n) -} - -// SetTCTime sets the tree creation time (tctime) attribute of a node to the given time. -// Since decomposedfs does not differentiate between ctime and mtime, it sets the tree modification time (tmtime) instead. -func (dtm *Manager) SetTCTime(ctx context.Context, n *node.Node, tmtime *time.Time) error { - // decomposedfs does not differentiate between ctime and mtime - return dtm.SetTMTime(ctx, n, tmtime) -} - -// DTime retrieves the deletion time (dtime) attribute of a node. -func (dtm *Manager) DTime(ctx context.Context, n *node.Node) (tmTime time.Time, err error) { - b, err := n.XattrString(ctx, prefixes.DTimeAttr) - if err != nil { - return time.Time{}, err - } - return time.Parse(time.RFC3339Nano, b) -} - -// SetDTime sets the deletion time (dtime) attribute of a node to the given time. -// If the time is nil, the attribute is removed. -func (dtm *Manager) SetDTime(ctx context.Context, n *node.Node, t *time.Time) (err error) { - if t == nil { - return n.RemoveXattr(ctx, prefixes.DTimeAttr, true) - } - return n.SetXattrString(ctx, prefixes.DTimeAttr, t.UTC().Format(time.RFC3339Nano)) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin/trashbin.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin/trashbin.go deleted file mode 100644 index 3f17f0b6b2..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin/trashbin.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2018-2024 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package trashbin - -import ( - "context" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/storage" -) - -type Trashbin interface { - Setup(storage.FS) error - - ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) - RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error - PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error - EmptyRecycle(ctx context.Context, ref *provider.Reference) error -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/async.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/async.go deleted file mode 100644 index 2e0920c1c6..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/async.go +++ /dev/null @@ -1,439 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package propagator - -import ( - "context" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/google/renameio/v2" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/rs/zerolog" - "github.com/shamaton/msgpack/v2" -) - -var _propagationGracePeriod = 3 * time.Minute - -// AsyncPropagator implements asynchronous treetime & treesize propagation -type AsyncPropagator struct { - treeSizeAccounting bool - treeTimeAccounting bool - propagationDelay time.Duration - lookup node.PathLookup - log *zerolog.Logger -} - -// Change represents a change to the tree -type Change struct { - SyncTime time.Time - SizeDiff int64 -} - -// NewAsyncPropagator returns a new AsyncPropagator instance -func NewAsyncPropagator(treeSizeAccounting, treeTimeAccounting bool, o options.AsyncPropagatorOptions, lookup node.PathLookup, log *zerolog.Logger) AsyncPropagator { - p := AsyncPropagator{ - treeSizeAccounting: treeSizeAccounting, - treeTimeAccounting: treeTimeAccounting, - propagationDelay: o.PropagationDelay, - lookup: lookup, - log: log, - } - - log.Info().Msg("async propagator starting up...") - - // spawn a goroutine that watches for stale .processing dirs and fixes them - go func() { - if !p.treeTimeAccounting && !p.treeSizeAccounting { - // no propagation enabled - log.Debug().Msg("propagation disabled or nothing to propagate") - return - } - - changesDirPath := filepath.Join(p.lookup.InternalRoot(), "changes") - doSleep := false // switch to not sleep on the first iteration - for { - if doSleep { - time.Sleep(5 * time.Minute) - } - doSleep = true - log.Debug().Msg("scanning for stale .processing dirs") - - entries, err := filepath.Glob(changesDirPath + "/**/*") - if err != nil { - log.Error().Err(err).Msg("failed to list changes") - continue - } - - for _, e := range entries { - changesDirPath := e - entry, err := os.Stat(changesDirPath) - if err != nil { - continue - } - // recover all dirs that seem to have been stuck - if !entry.IsDir() || time.Now().Before(entry.ModTime().Add(_propagationGracePeriod)) { - continue - } - - go func() { - if !strings.HasSuffix(changesDirPath, ".processing") { - // first rename the existing node dir - err = os.Rename(changesDirPath, changesDirPath+".processing") - if err != nil { - return - } - changesDirPath += ".processing" - } - - log.Debug().Str("dir", changesDirPath).Msg("propagating stale .processing dir") - parts := strings.SplitN(entry.Name(), ":", 2) - if len(parts) != 2 { - log.Error().Str("file", entry.Name()).Msg("encountered invalid .processing dir") - return - } - - now := time.Now() - _ = os.Chtimes(changesDirPath, now, now) - p.propagate(context.Background(), parts[0], strings.TrimSuffix(parts[1], ".processing"), true, *log) - }() - } - } - }() - - return p -} - -// Propagate triggers a propagation -func (p AsyncPropagator) Propagate(ctx context.Context, n *node.Node, sizeDiff int64) error { - ctx, span := tracer.Start(ctx, "Propagate") - defer span.End() - log := appctx.GetLogger(ctx).With(). - Str("method", "async.Propagate"). - Str("spaceid", n.SpaceID). - Str("nodeid", n.ID). - Str("parentid", n.ParentID). - Int64("sizeDiff", sizeDiff). - Logger() - - if !p.treeTimeAccounting && (!p.treeSizeAccounting || sizeDiff == 0) { - // no propagation enabled - log.Debug().Msg("propagation disabled or nothing to propagate") - return nil - } - - // add a change to the parent node - c := Change{ - // use a sync time and don't rely on the mtime of the current node, as the stat might not change when a rename happened too quickly - SyncTime: time.Now().UTC(), - SizeDiff: sizeDiff, - } - go p.queuePropagation(ctx, n.SpaceID, n.ParentID, c, log) - - return nil -} - -func (p AsyncPropagator) queuePropagation(ctx context.Context, spaceID, nodeID string, change Change, log zerolog.Logger) { - // add a change to the parent node - changePath := p.changesPath(spaceID, nodeID, uuid.New().String()+".mpk") - - data, err := msgpack.Marshal(change) - if err != nil { - log.Error().Err(err).Msg("failed to marshal Change") - return - } - - _, subspan := tracer.Start(ctx, "write changes file") - ready := false - triggerPropagation := false - _ = os.MkdirAll(filepath.Dir(filepath.Dir(changePath)), 0700) - err = os.Mkdir(filepath.Dir(changePath), 0700) - triggerPropagation = err == nil || os.IsExist(err) // only the first goroutine, which succeeds to create the directory, is supposed to actually trigger the propagation - for retries := 0; retries <= 500; retries++ { - err := renameio.WriteFile(changePath, data, 0644) - if err == nil { - ready = true - break - } - log.Debug().Err(err).Msg("failed to write Change to disk (retrying)") - err = os.Mkdir(filepath.Dir(changePath), 0700) - triggerPropagation = err == nil || os.IsExist(err) // only the first goroutine, which succeeds to create the directory, is supposed to actually trigger the propagation - } - - if !ready { - log.Error().Err(err).Msg("failed to write Change to disk") - return - } - subspan.End() - - if !triggerPropagation { - return - } - - _, subspan = tracer.Start(ctx, "delay propagation") - time.Sleep(p.propagationDelay) // wait a moment before propagating - subspan.End() - - log.Debug().Msg("propagating") - // add a change to the parent node - changeDirPath := p.changesPath(spaceID, nodeID, "") - - // first rename the existing node dir - err = os.Rename(changeDirPath, changeDirPath+".processing") - if err != nil { - // This can fail in 2 ways - // 1. source does not exist anymore as it has already been propagated by another goroutine - // -> ignore, as the change is already being processed - // 2. target already exists because a previous propagation is still running - // -> ignore, the previous propagation will pick the new changes up - return - } - p.propagate(ctx, spaceID, nodeID, false, log) -} - -func (p AsyncPropagator) propagate(ctx context.Context, spaceID, nodeID string, recalculateTreeSize bool, log zerolog.Logger) { - changeDirPath := p.changesPath(spaceID, nodeID, "") - processingPath := changeDirPath + ".processing" - - cleanup := func() { - err := os.RemoveAll(processingPath) - if err != nil { - log.Error().Err(err).Msg("Could not remove .processing dir") - } - } - - _, subspan := tracer.Start(ctx, "list changes files") - d, err := os.Open(processingPath) - if err != nil { - log.Error().Err(err).Msg("Could not open change .processing dir") - cleanup() - return - } - defer d.Close() - names, err := d.Readdirnames(0) - if err != nil { - log.Error().Err(err).Msg("Could not read dirnames") - cleanup() - return - } - subspan.End() - - _, subspan = tracer.Start(ctx, "read changes files") - pc := Change{} - for _, name := range names { - if !strings.HasSuffix(name, ".mpk") { - continue - } - - b, err := os.ReadFile(filepath.Join(processingPath, name)) - if err != nil { - log.Error().Err(err).Msg("Could not read change") - cleanup() - return - } - c := Change{} - err = msgpack.Unmarshal(b, &c) - if err != nil { - log.Error().Err(err).Msg("Could not unmarshal change") - cleanup() - return - } - if c.SyncTime.After(pc.SyncTime) { - pc.SyncTime = c.SyncTime - } - pc.SizeDiff += c.SizeDiff - } - subspan.End() - - // TODO do we need to write an aggregated parentchange file? - - attrs := node.Attributes{} - - var f *lockedfile.File - // lock parent before reading treesize or tree time - nodePath := filepath.Join(p.lookup.InternalRoot(), "spaces", lookup.Pathify(spaceID, 1, 2), "nodes", lookup.Pathify(nodeID, 4, 2)) - - _, subspan = tracer.Start(ctx, "lockedfile.OpenFile") - lockFilepath := p.lookup.MetadataBackend().LockfilePath(nodePath) - f, err = lockedfile.OpenFile(lockFilepath, os.O_RDWR|os.O_CREATE, 0600) - subspan.End() - if err != nil { - log.Error().Err(err). - Str("lock filepath", lockFilepath). - Msg("Propagation failed. Could not open metadata for node with lock.") - cleanup() - return - } - // always log error if closing node fails - defer func() { - // ignore already closed error - cerr := f.Close() - if err == nil && cerr != nil && !errors.Is(cerr, os.ErrClosed) { - err = cerr // only overwrite err with en error from close if the former was nil - } - }() - - _, subspan = tracer.Start(ctx, "node.ReadNode") - var n *node.Node - if n, err = node.ReadNode(ctx, p.lookup, spaceID, nodeID, false, nil, false); err != nil { - log.Error().Err(err). - Msg("Propagation failed. Could not read node.") - cleanup() - return - } - subspan.End() - - if !n.Exists { - log.Debug().Str("attr", prefixes.PropagationAttr).Msg("node does not exist anymore, not propagating") - cleanup() - return - } - - if !n.HasPropagation(ctx) { - log.Debug().Str("attr", prefixes.PropagationAttr).Msg("propagation attribute not set or unreadable, not propagating") - cleanup() - return - } - - if p.treeTimeAccounting { - // update the parent tree time if it is older than the nodes mtime - updateSyncTime := false - - var tmTime time.Time - tmTime, err = n.GetTMTime(ctx) - switch { - case err != nil: - // missing attribute, or invalid format, overwrite - log.Debug().Err(err). - Msg("could not read tmtime attribute, overwriting") - updateSyncTime = true - case tmTime.Before(pc.SyncTime): - log.Debug(). - Time("tmtime", tmTime). - Time("stime", pc.SyncTime). - Msg("parent tmtime is older than node mtime, updating") - updateSyncTime = true - default: - log.Debug(). - Time("tmtime", tmTime). - Time("stime", pc.SyncTime). - Dur("delta", pc.SyncTime.Sub(tmTime)). - Msg("node tmtime is younger than stime, not updating") - } - - if updateSyncTime { - // update the tree time of the parent node - attrs.SetString(prefixes.TreeMTimeAttr, pc.SyncTime.UTC().Format(time.RFC3339Nano)) - } - - attrs.SetString(prefixes.TmpEtagAttr, "") - } - - // size accounting - if p.treeSizeAccounting && pc.SizeDiff != 0 { - var newSize uint64 - - // read treesize - treeSize, err := n.GetTreeSize(ctx) - switch { - case recalculateTreeSize || metadata.IsAttrUnset(err): - // fallback to calculating the treesize - log.Warn().Msg("treesize attribute unset, falling back to calculating the treesize") - newSize, err = calculateTreeSize(ctx, p.lookup, n.InternalPath()) - if err != nil { - log.Error().Err(err). - Msg("Error when calculating treesize of node.") // FIXME wat? - cleanup() - return - } - case err != nil: - log.Error().Err(err). - Msg("Failed to propagate treesize change. Error when reading the treesize attribute from node") - cleanup() - return - case pc.SizeDiff > 0: - newSize = treeSize + uint64(pc.SizeDiff) - case uint64(-pc.SizeDiff) > treeSize: - // The sizeDiff is larger than the current treesize. Which would result in - // a negative new treesize. Something must have gone wrong with the accounting. - // Reset the current treesize to 0. - log.Error().Uint64("treeSize", treeSize).Int64("sizeDiff", pc.SizeDiff). - Msg("Error when updating treesize of node. Updated treesize < 0. Resetting to 0") - newSize = 0 - default: - newSize = treeSize - uint64(-pc.SizeDiff) - } - - // update the tree size of the node - attrs.SetString(prefixes.TreesizeAttr, strconv.FormatUint(newSize, 10)) - log.Debug().Uint64("newSize", newSize).Msg("updated treesize of node") - } - - if err = n.SetXattrsWithContext(ctx, attrs, false); err != nil { - log.Error().Err(err).Msg("Failed to update extend attributes of node") - cleanup() - return - } - - // Release node lock early, ignore already closed error - _, subspan = tracer.Start(ctx, "f.Close") - cerr := f.Close() - subspan.End() - if cerr != nil && !errors.Is(cerr, os.ErrClosed) { - log.Error().Err(cerr).Msg("Failed to close node and release lock") - } - - log.Info().Msg("Propagation done. cleaning up") - cleanup() - - if !n.IsSpaceRoot(ctx) { - p.queuePropagation(ctx, n.SpaceID, n.ParentID, pc, log) - } - - // Check for a changes dir that might have been added meanwhile and pick it up - if _, err = os.Open(changeDirPath); err == nil { - log.Info().Msg("Found a new changes dir. starting next propagation") - time.Sleep(p.propagationDelay) // wait a moment before propagating - err = os.Rename(changeDirPath, processingPath) - if err != nil { - // This can fail in 2 ways - // 1. source does not exist anymore as it has already been propagated by another goroutine - // -> ignore, as the change is already being processed - // 2. target already exists because a previous propagation is still running - // -> ignore, the previous propagation will pick the new changes up - return - } - p.propagate(ctx, spaceID, nodeID, false, log) - } -} - -func (p AsyncPropagator) changesPath(spaceID, nodeID, filename string) string { - return filepath.Join(p.lookup.InternalRoot(), "changes", spaceID[0:2], spaceID+":"+nodeID, filename) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/propagator.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/propagator.go deleted file mode 100644 index 18cf32a328..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/propagator.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package propagator - -import ( - "context" - "os" - "path/filepath" - "strconv" - - sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/pkg/errors" - "github.com/rs/zerolog" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" -) - -var tracer trace.Tracer - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree/propagator") -} - -type Propagator interface { - Propagate(ctx context.Context, node *node.Node, sizediff int64) error -} - -func New(lookup node.PathLookup, o *options.Options, log *zerolog.Logger) Propagator { - switch o.Propagator { - case "async": - return NewAsyncPropagator(o.TreeSizeAccounting, o.TreeTimeAccounting, o.AsyncPropagatorOptions, lookup, log) - default: - return NewSyncPropagator(o.TreeSizeAccounting, o.TreeTimeAccounting, lookup) - } -} - -func calculateTreeSize(ctx context.Context, lookup node.PathLookup, childrenPath string) (uint64, error) { - ctx, span := tracer.Start(ctx, "calculateTreeSize") - defer span.End() - var size uint64 - - f, err := os.Open(childrenPath) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("childrenPath", childrenPath).Msg("could not open dir") - return 0, err - } - defer f.Close() - - names, err := f.Readdirnames(0) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("childrenPath", childrenPath).Msg("could not read dirnames") - return 0, err - } - for i := range names { - cPath := filepath.Join(childrenPath, names[i]) - resolvedPath, err := filepath.EvalSymlinks(cPath) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("childpath", cPath).Msg("could not resolve child entry symlink") - continue // continue after an error - } - - // raw read of the attributes for performance reasons - attribs, err := lookup.MetadataBackend().All(ctx, resolvedPath) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("childpath", cPath).Msg("could not read attributes of child entry") - continue // continue after an error - } - sizeAttr := "" - if string(attribs[prefixes.TypeAttr]) == strconv.FormatUint(uint64(sprovider.ResourceType_RESOURCE_TYPE_FILE), 10) { - sizeAttr = string(attribs[prefixes.BlobsizeAttr]) - } else { - sizeAttr = string(attribs[prefixes.TreesizeAttr]) - } - csize, err := strconv.ParseInt(sizeAttr, 10, 64) - if err != nil { - return 0, errors.Wrapf(err, "invalid blobsize xattr format") - } - size += uint64(csize) - } - return size, err -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/sync.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/sync.go deleted file mode 100644 index 4646c3358c..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator/sync.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package propagator - -import ( - "context" - "errors" - "os" - "strconv" - "time" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/rs/zerolog" -) - -// SyncPropagator implements synchronous treetime & treesize propagation -type SyncPropagator struct { - treeSizeAccounting bool - treeTimeAccounting bool - lookup node.PathLookup -} - -// NewSyncPropagator returns a new AsyncPropagator instance -func NewSyncPropagator(treeSizeAccounting, treeTimeAccounting bool, lookup node.PathLookup) SyncPropagator { - return SyncPropagator{ - treeSizeAccounting: treeSizeAccounting, - treeTimeAccounting: treeTimeAccounting, - lookup: lookup, - } -} - -// Propagate triggers a propagation -func (p SyncPropagator) Propagate(ctx context.Context, n *node.Node, sizeDiff int64) error { - ctx, span := tracer.Start(ctx, "Propagate") - defer span.End() - sublog := appctx.GetLogger(ctx).With(). - Str("method", "sync.Propagate"). - Str("spaceid", n.SpaceID). - Str("nodeid", n.ID). - Int64("sizeDiff", sizeDiff). - Logger() - - if !p.treeTimeAccounting && (!p.treeSizeAccounting || sizeDiff == 0) { - // no propagation enabled - sublog.Debug().Msg("propagation disabled or nothing to propagate") - return nil - } - - // is propagation enabled for the parent node? - root := n.SpaceRoot - - // use a sync time and don't rely on the mtime of the current node, as the stat might not change when a rename happened too quickly - sTime := time.Now().UTC() - - // we loop until we reach the root - var ( - err error - stop bool - ) - - for err == nil && !stop && n.ID != root.ID { - n, stop, err = p.propagateItem(ctx, n, sTime, sizeDiff, sublog) - } - - if err != nil { - sublog.Error().Err(err).Msg("error propagating") - return err - } - return nil -} - -func (p SyncPropagator) propagateItem(ctx context.Context, n *node.Node, sTime time.Time, sizeDiff int64, log zerolog.Logger) (*node.Node, bool, error) { - log.Debug().Msg("propagating") - - attrs := node.Attributes{} - - var f *lockedfile.File - // lock parent before reading treesize or tree time - - _, subspan := tracer.Start(ctx, "lockedfile.OpenFile") - parentFilename := p.lookup.MetadataBackend().LockfilePath(n.ParentPath()) - f, err := lockedfile.OpenFile(parentFilename, os.O_RDWR|os.O_CREATE, 0600) - subspan.End() - if err != nil { - log.Error().Err(err). - Str("parent filename", parentFilename). - Msg("Propagation failed. Could not open metadata for parent with lock.") - return nil, true, err - } - // always log error if closing node fails - defer func() { - // ignore already closed error - cerr := f.Close() - if err == nil && cerr != nil && !errors.Is(cerr, os.ErrClosed) { - err = cerr // only overwrite err with en error from close if the former was nil - } - }() - - if n, err = n.Parent(ctx); err != nil { - log.Error().Err(err). - Msg("Propagation failed. Could not read parent node.") - return n, true, err - } - - if !n.HasPropagation(ctx) { - log.Debug().Str("attr", prefixes.PropagationAttr).Msg("propagation attribute not set or unreadable, not propagating") - // if the attribute is not set treat it as false / none / no propagation - return n, true, nil - } - - log = log.With().Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Logger() - - if p.treeTimeAccounting { - // update the parent tree time if it is older than the nodes mtime - updateSyncTime := false - - var tmTime time.Time - tmTime, err = n.GetTMTime(ctx) - switch { - case err != nil: - // missing attribute, or invalid format, overwrite - log.Debug().Err(err). - Msg("could not read tmtime attribute, overwriting") - updateSyncTime = true - case tmTime.Before(sTime): - log.Debug(). - Time("tmtime", tmTime). - Time("stime", sTime). - Msg("parent tmtime is older than node mtime, updating") - updateSyncTime = true - default: - log.Debug(). - Time("tmtime", tmTime). - Time("stime", sTime). - Dur("delta", sTime.Sub(tmTime)). - Msg("parent tmtime is younger than node mtime, not updating") - } - - if updateSyncTime { - // update the tree time of the parent node - attrs.SetString(prefixes.TreeMTimeAttr, sTime.UTC().Format(time.RFC3339Nano)) - } - - attrs.SetString(prefixes.TmpEtagAttr, "") - } - - // size accounting - if p.treeSizeAccounting && sizeDiff != 0 { - var newSize uint64 - - // read treesize - treeSize, err := n.GetTreeSize(ctx) - switch { - case metadata.IsAttrUnset(err): - // fallback to calculating the treesize - log.Warn().Msg("treesize attribute unset, falling back to calculating the treesize") - newSize, err = calculateTreeSize(ctx, p.lookup, n.InternalPath()) - if err != nil { - return n, true, err - } - case err != nil: - log.Error().Err(err). - Msg("Faild to propagate treesize change. Error when reading the treesize attribute from parent") - return n, true, err - case sizeDiff > 0: - newSize = treeSize + uint64(sizeDiff) - case uint64(-sizeDiff) > treeSize: - // The sizeDiff is larger than the current treesize. Which would result in - // a negative new treesize. Something must have gone wrong with the accounting. - // Reset the current treesize to 0. - log.Error().Uint64("treeSize", treeSize).Int64("sizeDiff", sizeDiff). - Msg("Error when updating treesize of parent node. Updated treesize < 0. Reestting to 0") - newSize = 0 - default: - newSize = treeSize - uint64(-sizeDiff) - } - - // update the tree size of the node - attrs.SetString(prefixes.TreesizeAttr, strconv.FormatUint(newSize, 10)) - log.Debug().Uint64("newSize", newSize).Msg("updated treesize of parent node") - } - - if err = n.SetXattrsWithContext(ctx, attrs, false); err != nil { - log.Error().Err(err).Msg("Failed to update extend attributes of parent node") - return n, true, err - } - - return n, false, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/tree.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/tree.go deleted file mode 100644 index ef2a0ddf5e..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/tree.go +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package tree - -import ( - "bytes" - "context" - "fmt" - "io" - "io/fs" - "os" - "path/filepath" - "regexp" - "strings" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator" - "github.com/opencloud-eu/reva/v2/pkg/utils" - "github.com/pkg/errors" - "github.com/rs/zerolog" - "go-micro.dev/v4/store" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" - "golang.org/x/sync/errgroup" -) - -var tracer trace.Tracer - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree") -} - -// Blobstore defines an interface for storing blobs in a blobstore -type Blobstore interface { - // TODO(OCISDEV-901): remove Upload once FinishUploadDecomposed is replaced by the upload coordinator (OCISDEV-900). - Upload(node *node.Node, source string) error - UploadFromReader(node *node.Node, r io.Reader, size int64) error - Download(node *node.Node) (io.ReadCloser, error) - Delete(node *node.Node) error -} - -// Tree manages a hierarchical tree -type Tree struct { - lookup node.PathLookup - blobstore Blobstore - propagator propagator.Propagator - - options *options.Options - - idCache store.Store -} - -// PermissionCheckFunc defined a function used to check resource permissions -type PermissionCheckFunc func(rp *provider.ResourcePermissions) bool - -// New returns a new instance of Tree -func New(lu node.PathLookup, bs Blobstore, o *options.Options, cache store.Store, log *zerolog.Logger) *Tree { - return &Tree{ - lookup: lu, - blobstore: bs, - options: o, - idCache: cache, - propagator: propagator.New(lu, o, log), - } -} - -// Setup prepares the tree structure -func (t *Tree) Setup() error { - // create data paths for internal layout - dataPaths := []string{ - filepath.Join(t.options.Root, "spaces"), - // notes contain symlinks from nodes//uploads/ to ../../uploads/ - // better to keep uploads on a fast / volatile storage before a workflow finally moves them to the nodes dir - filepath.Join(t.options.Root, "uploads"), - } - for _, v := range dataPaths { - err := os.MkdirAll(v, 0700) - if err != nil { - return err - } - } - return nil -} - -// GetMD returns the metadata of a node in the tree -func (t *Tree) GetMD(ctx context.Context, n *node.Node) (os.FileInfo, error) { - _, span := tracer.Start(ctx, "GetMD") - defer span.End() - md, err := os.Stat(n.InternalPath()) - if err != nil { - if errors.Is(err, fs.ErrNotExist) { - return nil, errtypes.NotFound(n.ID) - } - return nil, errors.Wrap(err, "tree: error stating "+n.ID) - } - - return md, nil -} - -// TouchFile creates a new empty file -func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool, mtime string) error { - _, span := tracer.Start(ctx, "TouchFile") - defer span.End() - if n.Exists { - if markprocessing { - return n.SetXattr(ctx, prefixes.StatusPrefix, []byte(node.ProcessingStatus)) - } - - return errtypes.AlreadyExists(n.ID) - } - - if n.ID == "" { - n.ID = uuid.New().String() - } - n.SetType(provider.ResourceType_RESOURCE_TYPE_FILE) - - nodePath := n.InternalPath() - if err := os.MkdirAll(filepath.Dir(nodePath), 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating node") - } - _, err := os.Create(nodePath) - if err != nil { - return errors.Wrap(err, "Decomposedfs: error creating node") - } - - attributes := n.NodeMetadata(ctx) - if markprocessing { - attributes[prefixes.StatusPrefix] = []byte(node.ProcessingStatus) - } - if mtime != "" { - if err := n.SetMtimeString(ctx, mtime); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set mtime") - } - } else { - now := time.Now() - if err := n.SetMtime(ctx, &now); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set mtime") - } - } - err = n.SetXattrsWithContext(ctx, attributes, true) - if err != nil { - return err - } - - // link child name to parent if it is new - childNameLink := filepath.Join(n.ParentPath(), n.Name) - var link string - link, err = os.Readlink(childNameLink) - if err == nil && link != "../"+n.ID { - if err = os.Remove(childNameLink); err != nil { - return errors.Wrap(err, "Decomposedfs: could not remove symlink child entry") - } - } - if errors.Is(err, fs.ErrNotExist) || link != "../"+n.ID { - relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2)) - if err = os.Symlink(relativeNodePath, childNameLink); err != nil { - return errors.Wrap(err, "Decomposedfs: could not symlink child entry") - } - } - - return t.Propagate(ctx, n, 0) -} - -// CreateDir creates a new directory entry in the tree -func (t *Tree) CreateDir(ctx context.Context, n *node.Node) (err error) { - ctx, span := tracer.Start(ctx, "CreateDir") - defer span.End() - if n.Exists { - return errtypes.AlreadyExists(n.ID) // path? - } - - // create a directory node - n.SetType(provider.ResourceType_RESOURCE_TYPE_CONTAINER) - if n.ID == "" { - n.ID = uuid.New().String() - } - - err = t.createDirNode(ctx, n) - if err != nil { - return - } - - // make child appear in listings - relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2)) - ctx, subspan := tracer.Start(ctx, "os.Symlink") - err = os.Symlink(relativeNodePath, filepath.Join(n.ParentPath(), n.Name)) - subspan.End() - if err != nil { - // no better way to check unfortunately - if !strings.Contains(err.Error(), "file exists") { - return - } - - // try to remove the node - ctx, subspan = tracer.Start(ctx, "os.RemoveAll") - e := os.RemoveAll(n.InternalPath()) - subspan.End() - if e != nil { - appctx.GetLogger(ctx).Debug().Err(e).Msg("cannot delete node") - } - return errtypes.AlreadyExists(err.Error()) - } - return t.Propagate(ctx, n, 0) -} - -// Move replaces the target with the source -func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) (err error) { - _, span := tracer.Start(ctx, "Move") - defer span.End() - if oldNode.SpaceID != newNode.SpaceID { - // WebDAV RFC https://www.rfc-editor.org/rfc/rfc4918#section-9.9.4 says to use - // > 502 (Bad Gateway) - This may occur when the destination is on another - // > server and the destination server refuses to accept the resource. - // > This could also occur when the destination is on another sub-section - // > of the same server namespace. - // but we only have a not supported error - return errtypes.NotSupported("cannot move across spaces") - } - // if target exists delete it without trashing it - if newNode.Exists { - // TODO make sure all children are deleted - if err := os.RemoveAll(newNode.InternalPath()); err != nil { - return errors.Wrap(err, "Decomposedfs: Move: error deleting target node "+newNode.ID) - } - } - - // remove cache entry in any case to avoid inconsistencies - defer func() { _ = t.idCache.Delete(filepath.Join(oldNode.ParentPath(), oldNode.Name)) }() - - // Always target the old node ID for xattr updates. - // The new node id is empty if the target does not exist - // and we need to overwrite the new one when overwriting an existing path. - // are we just renaming (parent stays the same)? - if oldNode.ParentID == newNode.ParentID { - - // parentPath := t.lookup.InternalPath(oldNode.SpaceID, oldNode.ParentID) - parentPath := oldNode.ParentPath() - - // rename child - err = os.Rename( - filepath.Join(parentPath, oldNode.Name), - filepath.Join(parentPath, newNode.Name), - ) - if err != nil { - return errors.Wrap(err, "Decomposedfs: could not rename child") - } - - // update name attribute - if err := oldNode.SetXattrString(ctx, prefixes.NameAttr, newNode.Name); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") - } - - return t.Propagate(ctx, newNode, 0) - } - - // we are moving the node to a new parent, any target has been removed - // bring old node to the new parent - - // rename child - err = os.Rename( - filepath.Join(oldNode.ParentPath(), oldNode.Name), - filepath.Join(newNode.ParentPath(), newNode.Name), - ) - if err != nil { - return errors.Wrap(err, "Decomposedfs: could not move child") - } - - // update target parentid and name - attribs := node.Attributes{} - attribs.SetString(prefixes.ParentidAttr, newNode.ParentID) - attribs.SetString(prefixes.NameAttr, newNode.Name) - if err := oldNode.SetXattrsWithContext(ctx, attribs, true); err != nil { - return errors.Wrap(err, "Decomposedfs: could not update old node attributes") - } - - // the size diff is the current treesize or blobsize of the old/source node - var sizeDiff int64 - if oldNode.IsDir(ctx) { - treeSize, err := oldNode.GetTreeSize(ctx) - if err != nil { - return err - } - sizeDiff = int64(treeSize) - } else { - sizeDiff = oldNode.Blobsize - } - - // TODO inefficient because we might update several nodes twice, only propagate unchanged nodes? - // collect in a list, then only stat each node once - // also do this in a go routine ... webdav should check the etag async - - err = t.Propagate(ctx, oldNode, -sizeDiff) - if err != nil { - return errors.Wrap(err, "Decomposedfs: Move: could not propagate old node") - } - err = t.Propagate(ctx, newNode, sizeDiff) - if err != nil { - return errors.Wrap(err, "Decomposedfs: Move: could not propagate new node") - } - return nil -} - -func readChildNodeFromLink(ctx context.Context, path string) (string, error) { - _, span := tracer.Start(ctx, "readChildNodeFromLink") - defer span.End() - link, err := os.Readlink(path) - if err != nil { - return "", err - } - nodeID := strings.TrimLeft(link, "/.") - nodeID = strings.ReplaceAll(nodeID, "/", "") - return nodeID, nil -} - -// ListFolder lists the content of a folder node -func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, error) { - ctx, span := tracer.Start(ctx, "ListFolder") - defer span.End() - dir := n.InternalPath() - - _, subspan := tracer.Start(ctx, "os.Open") - f, err := os.Open(dir) - subspan.End() - if err != nil { - if errors.Is(err, fs.ErrNotExist) { - return nil, errtypes.NotFound(dir) - } - return nil, errors.Wrap(err, "tree: error listing "+dir) - } - defer f.Close() - - _, subspan = tracer.Start(ctx, "f.Readdirnames") - names, err := f.Readdirnames(0) - subspan.End() - if err != nil { - return nil, err - } - - numWorkers := t.options.MaxConcurrency - if len(names) < numWorkers { - numWorkers = len(names) - } - work := make(chan string) - results := make(chan *node.Node) - - g, ctx := errgroup.WithContext(ctx) - - // Distribute work - g.Go(func() error { - defer close(work) - for _, name := range names { - select { - case work <- name: - case <-ctx.Done(): - return ctx.Err() - } - } - return nil - }) - - // Spawn workers that'll concurrently work the queue - for i := 0; i < numWorkers; i++ { - g.Go(func() error { - var err error - for name := range work { - path := filepath.Join(dir, name) - nodeID := getNodeIDFromCache(ctx, path, t.idCache) - if nodeID == "" { - nodeID, err = readChildNodeFromLink(ctx, path) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("path", path).Msg("cannot read node from link") - continue - } - err = storeNodeIDInCache(ctx, path, nodeID, t.idCache) - if err != nil { - appctx.GetLogger(ctx).Warn().Err(err).Str("node", nodeID).Msg("cannot store node in the cache") - // failing to write in the cache is fine because we can keep going - } - } - - child, err := node.ReadNode(ctx, t.lookup, n.SpaceID, nodeID, false, n.SpaceRoot, true) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("node", nodeID).Msg("cannot read node") - continue - } - - // prevent listing denied resources - if !child.IsDenied(ctx) { - if child.SpaceRoot == nil { - child.SpaceRoot = n.SpaceRoot - } - select { - case results <- child: - case <-ctx.Done(): - return ctx.Err() - } - } - } - return nil - }) - } - // Wait for things to settle down, then close results chan - go func() { - _ = g.Wait() // error is checked later - close(results) - }() - - retNodes := []*node.Node{} - for n := range results { - retNodes = append(retNodes, n) - } - - if err := g.Wait(); err != nil { - return nil, err - } - - return retNodes, nil -} - -// Delete deletes a node in the tree by moving it to the trash -func (t *Tree) Delete(ctx context.Context, n *node.Node) (err error) { - _, span := tracer.Start(ctx, "Delete") - defer span.End() - path := filepath.Join(n.ParentPath(), n.Name) - // remove entry from cache immediately to avoid inconsistencies - defer func() { _ = t.idCache.Delete(path) }() - - // get the original path - origin, err := t.lookup.Path(ctx, n, node.NoCheck) - if err != nil { - return - } - - // set origin location in metadata - nodePath := n.InternalPath() - if err := n.SetXattrString(ctx, prefixes.TrashOriginAttr, origin); err != nil { - return err - } - - var sizeDiff int64 - if n.IsDir(ctx) { - treesize, err := n.GetTreeSize(ctx) - if err != nil { - return err // TODO calculate treesize if it is not set - } - sizeDiff = -int64(treesize) - } else { - sizeDiff = -n.Blobsize - } - - deletionTime := time.Now().UTC().Format(time.RFC3339Nano) - - // Prepare the trash - trashLink := filepath.Join(t.options.Root, "spaces", lookup.Pathify(n.SpaceRoot.ID, 1, 2), "trash", lookup.Pathify(n.ID, 4, 2)) - if err := os.MkdirAll(filepath.Dir(trashLink), 0700); err != nil { - // Roll back changes - _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr, true) - return err - } - - // FIXME can we just move the node into the trash dir? instead of adding another symlink and appending a trash timestamp? - // can we just use the mtime as the trash time? - // TODO store a trashed by userid - - // first make node appear in the space trash - // parent id and name are stored as extended attributes in the node itself - err = os.Symlink("../../../../../nodes/"+lookup.Pathify(n.ID, 4, 2)+node.TrashIDDelimiter+deletionTime, trashLink) - if err != nil { - // Roll back changes - _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr, true) - return - } - - // at this point we have a symlink pointing to a non existing destination, which is fine - - // rename the trashed node so it is not picked up when traversing up the tree and matches the symlink - trashPath := nodePath + node.TrashIDDelimiter + deletionTime - err = os.Rename(nodePath, trashPath) - if err != nil { - // To roll back changes - // TODO remove symlink - // Roll back changes - _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr, true) - return - } - err = t.lookup.MetadataBackend().Rename(nodePath, trashPath) - if err != nil { - _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr, true) - _ = os.Rename(trashPath, nodePath) - return - } - - // Remove lock file if it exists - _ = os.Remove(n.LockFilePath()) - - // finally remove the entry from the parent dir - if err = os.Remove(path); err != nil { - // To roll back changes - // TODO revert the rename - // TODO remove symlink - // Roll back changes - _ = n.RemoveXattr(ctx, prefixes.TrashOriginAttr, true) - return - } - - return t.Propagate(ctx, n, sizeDiff) -} - -// RestoreRecycleItemFunc returns a node and a function to restore it from the trash. -func (t *Tree) RestoreRecycleItemFunc(ctx context.Context, spaceid, key, trashPath string, targetNode *node.Node) (*node.Node, *node.Node, func() error, error) { - _, span := tracer.Start(ctx, "RestoreRecycleItemFunc") - defer span.End() - logger := appctx.GetLogger(ctx) - - recycleNode, trashItem, deletedNodePath, origin, err := t.readRecycleItem(ctx, spaceid, key, trashPath) - if err != nil { - return nil, nil, nil, err - } - - targetRef := &provider.Reference{ - ResourceId: &provider.ResourceId{SpaceId: spaceid, OpaqueId: spaceid}, - Path: utils.MakeRelativePath(origin), - } - - if targetNode == nil { - targetNode, err = t.lookup.NodeFromResource(ctx, targetRef) - if err != nil { - return nil, nil, nil, err - } - } - - if err := targetNode.CheckLock(ctx); err != nil { - return nil, nil, nil, err - } - - parent, err := targetNode.Parent(ctx) - if err != nil { - return nil, nil, nil, err - } - - fn := func() error { - if targetNode.Exists { - return errtypes.AlreadyExists("origin already exists") - } - - // add the entry for the parent dir - err = os.Symlink("../../../../../"+lookup.Pathify(recycleNode.ID, 4, 2), filepath.Join(targetNode.ParentPath(), targetNode.Name)) - if err != nil { - return err - } - - // rename to node only name, so it is picked up by id - nodePath := recycleNode.InternalPath() - - // attempt to rename only if we're not in a subfolder - if deletedNodePath != nodePath { - err = os.Rename(deletedNodePath, nodePath) - if err != nil { - return err - } - err = t.lookup.MetadataBackend().Rename(deletedNodePath, nodePath) - if err != nil { - return err - } - } - - targetNode.Exists = true - - attrs := node.Attributes{} - attrs.SetString(prefixes.NameAttr, targetNode.Name) - // set ParentidAttr to restorePath's node parent id - attrs.SetString(prefixes.ParentidAttr, targetNode.ParentID) - - if err = recycleNode.SetXattrsWithContext(ctx, attrs, true); err != nil { - return errors.Wrap(err, "Decomposedfs: could not update recycle node") - } - - // delete item link in trash - deletePath := trashItem - if trashPath != "" && trashPath != "/" { - resolvedTrashRoot, err := filepath.EvalSymlinks(trashItem) - if err != nil { - return errors.Wrap(err, "Decomposedfs: could not resolve trash root") - } - deletePath = filepath.Join(resolvedTrashRoot, trashPath) - if err = os.Remove(deletePath); err != nil { - logger.Error().Err(err).Str("trashItem", trashItem).Str("deletePath", deletePath).Str("trashPath", trashPath).Msg("error deleting trash item") - } - } else { - if err = utils.RemoveItem(deletePath); err != nil { - logger.Error().Err(err).Str("trashItem", trashItem).Str("deletePath", deletePath).Str("trashPath", trashPath).Msg("error recursively deleting trash item") - } - } - - var sizeDiff int64 - if recycleNode.IsDir(ctx) { - treeSize, err := recycleNode.GetTreeSize(ctx) - if err != nil { - return err - } - sizeDiff = int64(treeSize) - } else { - sizeDiff = recycleNode.Blobsize - } - return t.Propagate(ctx, targetNode, sizeDiff) - } - return recycleNode, parent, fn, nil -} - -// PurgeRecycleItemFunc returns a node and a function to purge it from the trash -func (t *Tree) PurgeRecycleItemFunc(ctx context.Context, spaceid, key string, path string) (*node.Node, func() error, error) { - _, span := tracer.Start(ctx, "PurgeRecycleItemFunc") - defer span.End() - logger := appctx.GetLogger(ctx) - - rn, trashItem, deletedNodePath, _, err := t.readRecycleItem(ctx, spaceid, key, path) - if err != nil { - return nil, nil, err - } - - ts := "" - timeSuffix := strings.SplitN(filepath.Base(deletedNodePath), node.TrashIDDelimiter, 2) - if len(timeSuffix) == 2 { - ts = timeSuffix[1] - } - - fn := func() error { - - if err := t.removeNode(ctx, deletedNodePath, ts, rn); err != nil { - return err - } - - // delete item link in trash - deletePath := trashItem - if path != "" && path != "/" { - resolvedTrashRoot, err := filepath.EvalSymlinks(trashItem) - if err != nil { - return errors.Wrap(err, "Decomposedfs: could not resolve trash root") - } - deletePath = filepath.Join(resolvedTrashRoot, path) - } - if err = utils.RemoveItem(deletePath); err != nil { - logger.Error().Err(err).Str("deletePath", deletePath).Msg("error deleting trash item") - return err - } - - return nil - } - - return rn, fn, nil -} - -// InitNewNode initializes a new node -func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (metadata.UnlockFunc, error) { - _, span := tracer.Start(ctx, "InitNewNode") - defer span.End() - // create folder structure (if needed) - - _, subspan := tracer.Start(ctx, "os.MkdirAll") - err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700) - subspan.End() - if err != nil { - return nil, err - } - - // create and write lock new node metadata - _, subspan = tracer.Start(ctx, "metadata.Lock") - unlock, err := t.lookup.MetadataBackend().Lock(n.InternalPath()) - subspan.End() - if err != nil { - return nil, err - } - - // we also need to touch the actual node file here it stores the mtime of the resource - _, subspan = tracer.Start(ctx, "os.OpenFile") - h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600) - subspan.End() - if err != nil { - return unlock, err - } - h.Close() - - _, subspan = tracer.Start(ctx, "node.CheckQuota") - _, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize) - subspan.End() - if err != nil { - return unlock, err - } - - // link child name to parent if it is new - childNameLink := filepath.Join(n.ParentPath(), n.Name) - relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2)) - log := appctx.GetLogger(ctx).With().Str("childNameLink", childNameLink).Str("relativeNodePath", relativeNodePath).Logger() - log.Info().Msg("initNewNode: creating symlink") - - _, subspan = tracer.Start(ctx, "os.Symlink") - err = os.Symlink(relativeNodePath, childNameLink) - subspan.End() - if err != nil { - log.Info().Err(err).Msg("initNewNode: symlink failed") - if errors.Is(err, fs.ErrExist) { - log.Info().Err(err).Msg("initNewNode: symlink already exists") - return unlock, errtypes.AlreadyExists(n.Name) - } - return unlock, errors.Wrap(err, "Decomposedfs: could not symlink child entry") - } - log.Info().Msg("initNewNode: symlink created") - - return unlock, nil -} - -func (t *Tree) removeNode(ctx context.Context, path, timeSuffix string, n *node.Node) error { - logger := appctx.GetLogger(ctx) - - if timeSuffix != "" { - n.ID = n.ID + node.TrashIDDelimiter + timeSuffix - } - - if n.IsDir(ctx) { - item, err := t.ListFolder(ctx, n) - if err != nil { - logger.Error().Err(err).Str("path", path).Msg("error listing folder") - } else { - for _, child := range item { - if err := t.removeNode(ctx, child.InternalPath(), "", child); err != nil { - return err - } - } - } - } - - // delete the actual node - if err := utils.RemoveItem(path); err != nil { - logger.Error().Err(err).Str("path", path).Msg("error purging node") - return err - } - - if err := t.lookup.MetadataBackend().Purge(ctx, path); err != nil { - logger.Error().Err(err).Str("path", t.lookup.MetadataBackend().MetadataPath(path)).Msg("error purging node metadata") - return err - } - - // delete blob from blobstore - if n.BlobID != "" { - if err := t.DeleteBlob(n); err != nil { - logger.Error().Err(err).Str("blobID", n.BlobID).Msg("error purging nodes blob") - return err - } - } - - // delete revisions - revs, err := filepath.Glob(n.InternalPath() + node.RevisionIDDelimiter + "*") - if err != nil { - logger.Error().Err(err).Str("path", n.InternalPath()+node.RevisionIDDelimiter+"*").Msg("glob failed badly") - return err - } - for _, rev := range revs { - if t.lookup.MetadataBackend().IsMetaFile(rev) { - continue - } - - bID, _, err := t.lookup.ReadBlobIDAndSizeAttr(ctx, rev, nil) - if err != nil { - logger.Error().Err(err).Str("revision", rev).Msg("error reading blobid attribute") - return err - } - - if err := utils.RemoveItem(rev); err != nil { - logger.Error().Err(err).Str("revision", rev).Msg("error removing revision node") - return err - } - - if bID != "" { - if err := t.DeleteBlob(&node.Node{SpaceID: n.SpaceID, BlobID: bID}); err != nil { - logger.Error().Err(err).Str("revision", rev).Str("blobID", bID).Msg("error removing revision node blob") - return err - } - } - - } - - return nil -} - -// Propagate propagates changes to the root of the tree -func (t *Tree) Propagate(ctx context.Context, n *node.Node, sizeDiff int64) (err error) { - return t.propagator.Propagate(ctx, n, sizeDiff) -} - -// WriteBlob writes a blob to the blobstore -// TODO(OCISDEV-901): remove once FinishUploadDecomposed is replaced by the upload coordinator (OCISDEV-900). -func (t *Tree) WriteBlob(node *node.Node, source string) error { - return t.blobstore.Upload(node, source) -} - -// WriteBlobFromReader writes a blob to the blobstore from a reader -func (t *Tree) WriteBlobFromReader(node *node.Node, r io.Reader, size int64) error { - return t.blobstore.UploadFromReader(node, r, size) -} - -// ReadBlob reads a blob from the blobstore -func (t *Tree) ReadBlob(node *node.Node) (io.ReadCloser, error) { - if node.BlobID == "" { - // there is no blob yet - we are dealing with a 0 byte file - return io.NopCloser(bytes.NewReader([]byte{})), nil - } - return t.blobstore.Download(node) -} - -// DeleteBlob deletes a blob from the blobstore -func (t *Tree) DeleteBlob(node *node.Node) error { - if node == nil { - return fmt.Errorf("could not delete blob, nil node was given") - } - if node.BlobID == "" { - return fmt.Errorf("could not delete blob, node with empty blob id was given") - } - - return t.blobstore.Delete(node) -} - -// BuildSpaceIDIndexEntry returns the entry for the space id index -func (t *Tree) BuildSpaceIDIndexEntry(spaceID, nodeID string) string { - return "../../../spaces/" + lookup.Pathify(spaceID, 1, 2) + "/nodes/" + lookup.Pathify(spaceID, 4, 2) -} - -// ResolveSpaceIDIndexEntry returns the node id for the space id index entry -func (t *Tree) ResolveSpaceIDIndexEntry(_, entry string) (string, string, error) { - return ReadSpaceAndNodeFromIndexLink(entry) -} - -// ReadSpaceAndNodeFromIndexLink reads a symlink and parses space and node id if the link has the correct format, eg: -// ../../spaces/4c/510ada-c86b-4815-8820-42cdf82c3d51/nodes/4c/51/0a/da/-c86b-4815-8820-42cdf82c3d51 -// ../../spaces/4c/510ada-c86b-4815-8820-42cdf82c3d51/nodes/4c/51/0a/da/-c86b-4815-8820-42cdf82c3d51.T.2022-02-24T12:35:18.196484592Z -func ReadSpaceAndNodeFromIndexLink(link string) (string, string, error) { - // ../../../spaces/sp/ace-id/nodes/sh/or/tn/od/eid - // 0 1 2 3 4 5 6 7 8 9 10 11 - parts := strings.Split(link, string(filepath.Separator)) - if len(parts) != 12 || parts[0] != ".." || parts[1] != ".." || parts[2] != ".." || parts[3] != "spaces" || parts[6] != "nodes" { - return "", "", errtypes.InternalError("malformed link") - } - return strings.Join(parts[4:6], ""), strings.Join(parts[7:12], ""), nil -} - -// TODO check if node exists? -func (t *Tree) createDirNode(ctx context.Context, n *node.Node) (err error) { - ctx, span := tracer.Start(ctx, "createDirNode") - defer span.End() - // create a directory node - nodePath := n.InternalPath() - if err := os.MkdirAll(nodePath, 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating node") - } - - attributes := n.NodeMetadata(ctx) - attributes[prefixes.SpaceIDAttr] = []byte(n.SpaceID) - attributes[prefixes.TreesizeAttr] = []byte("0") // initialize as empty, TODO why bother? if it is not set we could treat it as 0? - if t.options.TreeTimeAccounting || t.options.TreeSizeAccounting { - attributes[prefixes.PropagationAttr] = []byte("1") // mark the node for propagation - } - return n.SetXattrsWithContext(ctx, attributes, true) -} - -var nodeIDRegep = regexp.MustCompile(`.*/nodes/([^.]*).*`) - -// TODO refactor the returned params into Node properties? would make all the path transformations go away... -func (t *Tree) readRecycleItem(ctx context.Context, spaceID, key, path string) (recycleNode *node.Node, trashItem string, deletedNodePath string, origin string, err error) { - _, span := tracer.Start(ctx, "readRecycleItem") - defer span.End() - logger := appctx.GetLogger(ctx) - - if key == "" { - return nil, "", "", "", errtypes.InternalError("key is empty") - } - - backend := t.lookup.MetadataBackend() - var nodeID string - - trashItem = filepath.Join(t.lookup.InternalRoot(), "spaces", lookup.Pathify(spaceID, 1, 2), "trash", lookup.Pathify(key, 4, 2)) - resolvedTrashItem, err := filepath.EvalSymlinks(trashItem) - if err != nil { - return - } - deletedNodePath, err = filepath.EvalSymlinks(filepath.Join(resolvedTrashItem, path)) - if err != nil { - return - } - nodeID = nodeIDRegep.ReplaceAllString(deletedNodePath, "$1") - nodeID = strings.ReplaceAll(nodeID, "/", "") - - recycleNode = node.New(spaceID, nodeID, "", "", 0, "", provider.ResourceType_RESOURCE_TYPE_INVALID, nil, t.lookup) - recycleNode.SpaceRoot, err = node.ReadNode(ctx, t.lookup, spaceID, spaceID, false, nil, false) - if err != nil { - return - } - recycleNode.SetType(t.lookup.TypeFromPath(ctx, deletedNodePath)) - - var attrBytes []byte - if recycleNode.Type(ctx) == provider.ResourceType_RESOURCE_TYPE_FILE { - // lookup blobID in extended attributes - if attrBytes, err = backend.Get(ctx, deletedNodePath, prefixes.BlobIDAttr); err == nil { - recycleNode.BlobID = string(attrBytes) - } else { - return - } - - // lookup blobSize in extended attributes - if recycleNode.Blobsize, err = backend.GetInt64(ctx, deletedNodePath, prefixes.BlobsizeAttr); err != nil { - return - } - } - - // lookup parent id in extended attributes - if attrBytes, err = backend.Get(ctx, deletedNodePath, prefixes.ParentidAttr); err == nil { - recycleNode.ParentID = string(attrBytes) - } else { - return - } - - // lookup name in extended attributes - if attrBytes, err = backend.Get(ctx, deletedNodePath, prefixes.NameAttr); err == nil { - recycleNode.Name = string(attrBytes) - } else { - return - } - - // get origin node, is relative to space root - origin = "/" - - // lookup origin path in extended attributes - if attrBytes, err = backend.Get(ctx, resolvedTrashItem, prefixes.TrashOriginAttr); err == nil { - origin = filepath.Join(string(attrBytes), path) - } else { - logger.Error().Err(err).Str("trashItem", trashItem).Str("deletedNodePath", deletedNodePath).Msg("could not read origin path, restoring to /") - } - - return -} - -func getNodeIDFromCache(ctx context.Context, path string, cache store.Store) string { - _, span := tracer.Start(ctx, "getNodeIDFromCache") - defer span.End() - recs, err := cache.Read(path) - if err == nil && len(recs) > 0 { - return string(recs[0].Value) - } - return "" -} - -func storeNodeIDInCache(ctx context.Context, path string, nodeID string, cache store.Store) error { - _, span := tracer.Start(ctx, "storeNodeIDInCache") - defer span.End() - return cache.Write(&store.Record{ - Key: path, - Value: []byte(nodeID), - }) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload.go deleted file mode 100644 index e44c564a65..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload.go +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package decomposedfs - -import ( - "context" - "fmt" - "os" - "path/filepath" - "strings" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - tusd "github.com/tus/tusd/v2/pkg/handler" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload" - "github.com/opencloud-eu/reva/v2/pkg/storagespace" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -// Upload uploads data to the given resource -// TODO(OCISDEV-901): remove Upload once all drivers are migrated to CommitUpload and the coordinator (OCISDEV-900) is in place. -func (fs *Decomposedfs) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) { - _, span := tracer.Start(ctx, "Upload") - defer span.End() - up, err := fs.GetUpload(ctx, req.Ref.GetPath()) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error retrieving upload") - } - - session := up.(*upload.OcisSession) - - ctx = session.Context(ctx) - - if session.Chunk() != "" { // check chunking v1 - p, assembledFile, err := fs.chunkHandler.WriteChunk(session.Chunk(), req.Body) - if err != nil { - return &provider.ResourceInfo{}, err - } - if p == "" { - if err = session.Terminate(ctx); err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error removing auxiliary files") - } - return &provider.ResourceInfo{}, errtypes.PartialContent(req.Ref.String()) - } - fd, err := os.Open(assembledFile) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error opening assembled file") - } - defer fd.Close() - defer os.RemoveAll(assembledFile) - req.Body = fd - - size, err := session.WriteChunk(ctx, 0, req.Body) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error writing to binary file") - } - session.SetSize(size) - } else { - size, err := session.WriteChunk(ctx, 0, req.Body) - if err != nil { - return &provider.ResourceInfo{}, errors.Wrap(err, "Decomposedfs: error writing to binary file") - } - if size != req.Length { - return &provider.ResourceInfo{}, errtypes.PartialContent("Decomposedfs: unexpected end of stream") - } - } - - if err := session.FinishUploadDecomposed(ctx); err != nil { - return &provider.ResourceInfo{}, err - } - - if uff != nil { - uploadRef := &provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.SpaceID(), - }, - Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())), - } - executant := session.Executant() - uff(session.SpaceOwner(), &executant, uploadRef) - } - - ri := &provider.ResourceInfo{ - // fill with at least fileid, mtime and etag - Id: &provider.ResourceId{ - StorageId: session.ProviderID(), - SpaceId: session.SpaceID(), - OpaqueId: session.NodeID(), - }, - } - - // add etag to metadata - ri.Etag, _ = node.CalculateEtag(session.NodeID(), session.MTime()) - - if !session.MTime().IsZero() { - ri.Mtime = utils.TimeToTS(session.MTime()) - } - - return ri, nil -} - -// InitiateUpload returns upload ids corresponding to different protocols it supports -// TODO(OCISDEV-901): remove InitiateUpload once all drivers are migrated to CommitUpload and the coordinator (OCISDEV-900) is in place. -func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - _, span := tracer.Start(ctx, "InitiateUpload") - defer span.End() - log := appctx.GetLogger(ctx) - - // remember the path from the reference - refpath := ref.GetPath() - var chunk *chunking.ChunkBLOBInfo - var err error - if chunking.IsChunked(refpath) { // check chunking v1 - chunk, err = chunking.GetChunkBLOBInfo(refpath) - if err != nil { - return nil, errtypes.BadRequest(err.Error()) - } - ref.Path = chunk.Path - } - n, err := fs.lu.NodeFromResource(ctx, ref) - switch err.(type) { - case nil: - // ok - case errtypes.IsNotFound: - return nil, errtypes.PreconditionFailed(err.Error()) - default: - return nil, err - } - - // permissions are checked in NewUpload below - - relative, err := fs.lu.Path(ctx, n, node.NoCheck) - // TODO why do we need the path here? - // jfd: it is used later when emitting the UploadReady event ... - // AAAND refPath might be . when accessing with an id / relative reference ... which causes NodeName to become . But then dir will also always be . - // That is why we still have to read the path here: so that the event we emit contains a relative reference with a path relative to the space root. WTF - if err != nil { - return nil, err - } - - lockID, _ := ctxpkg.ContextGetLockID(ctx) - - session := fs.sessionStore.New(ctx) - session.SetMetadata("filename", n.Name) - session.SetStorageValue("NodeName", n.Name) - if chunk != nil { - session.SetStorageValue("Chunk", filepath.Base(refpath)) - } - session.SetMetadata("dir", filepath.Dir(relative)) - session.SetStorageValue("Dir", filepath.Dir(relative)) - session.SetMetadata("lockid", lockID) - - session.SetSize(uploadLength) - session.SetStorageValue("SpaceRoot", n.SpaceRoot.ID) // TODO SpaceRoot -> SpaceID - session.SetStorageValue("SpaceOwnerOrManager", n.SpaceOwnerOrManager(ctx).GetOpaqueId()) // TODO needed for what? - - spaceGID, ok := ctx.Value(CtxKeySpaceGID).(uint32) - if ok { - session.SetStorageValue("SpaceGid", fmt.Sprintf("%d", spaceGID)) - } - - iid, _ := ctxpkg.ContextGetInitiator(ctx) - session.SetMetadata("initiatorid", iid) - - if metadata != nil { - session.SetMetadata("providerID", metadata["providerID"]) - if mtime, ok := metadata["mtime"]; ok { - if mtime != "null" { - session.SetMetadata("mtime", metadata["mtime"]) - } - } - if expiration, ok := metadata["expires"]; ok { - if expiration != "null" { - session.SetMetadata("expires", metadata["expires"]) - } - } - if _, ok := metadata["sizedeferred"]; ok { - session.SetSizeIsDeferred(true) - } - if checksum, ok := metadata["checksum"]; ok { - parts := strings.SplitN(checksum, " ", 2) - if len(parts) != 2 { - return nil, errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") - } - switch parts[0] { - case "sha1", "md5", "adler32": - session.SetMetadata("checksum", checksum) - default: - return nil, errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) - } - } - - // only check preconditions if they are not empty // TODO or is this a bad request? - if metadata["if-match"] != "" { - session.SetMetadata("if-match", metadata["if-match"]) - } - if metadata["if-none-match"] != "" { - session.SetMetadata("if-none-match", metadata["if-none-match"]) - } - if metadata["if-unmodified-since"] != "" { - session.SetMetadata("if-unmodified-since", metadata["if-unmodified-since"]) - } - } - - if session.MTime().IsZero() { - session.SetMetadata("mtime", utils.TimeToOCMtime(time.Now())) - } - - log.Debug().Str("uploadid", session.ID()).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Interface("metadata", metadata).Msg("Decomposedfs: resolved filename") - - _, err = node.CheckQuota(ctx, n.SpaceRoot, n.Exists, uint64(n.Blobsize), uint64(session.Size())) - if err != nil { - return nil, err - } - - if session.Filename() == "" { - return nil, errors.New("Decomposedfs: missing filename in metadata") - } - if session.Dir() == "" { - return nil, errors.New("Decomposedfs: missing dir in metadata") - } - - // the parent owner will become the new owner - parent, perr := n.Parent(ctx) - if perr != nil { - return nil, errors.Wrap(perr, "Decomposedfs: error getting parent "+n.ParentID) - } - - // check permissions - var ( - checkNode *node.Node - path string - ) - if n.Exists { - // check permissions of file to be overwritten - checkNode = n - path, _ = storagespace.FormatReference(&provider.Reference{ResourceId: &provider.ResourceId{ - SpaceId: checkNode.SpaceID, - OpaqueId: checkNode.ID, - }}) - } else { - // check permissions of parent - checkNode = parent - path, _ = storagespace.FormatReference(&provider.Reference{ResourceId: &provider.ResourceId{ - SpaceId: checkNode.SpaceID, - OpaqueId: checkNode.ID, - }, Path: n.Name}) - } - rp, err := fs.p.AssemblePermissions(ctx, checkNode) - switch { - case err != nil: - return nil, err - case !rp.InitiateFileUpload: - return nil, errtypes.PermissionDenied(path) - } - - // are we trying to overwriting a folder with a file? - if n.Exists && n.IsDir(ctx) { - return nil, errtypes.PreconditionFailed("resource is not a file") - } - - // check lock - if err := n.CheckLock(ctx); err != nil { - return nil, err - } - - usr := ctxpkg.ContextMustGetUser(ctx) - - // fill future node info - if n.Exists { - if session.HeaderIfNoneMatch() == "*" { - return nil, errtypes.Aborted(fmt.Sprintf("parent %s already has a child %s, id %s", n.ParentID, n.Name, n.ID)) - } - session.SetStorageValue("NodeId", n.ID) - session.SetStorageValue("NodeExists", "true") - } else { - session.SetStorageValue("NodeId", uuid.New().String()) - } - session.SetStorageValue("NodeParentId", n.ParentID) - session.SetExecutant(usr) - session.SetStorageValue("LogLevel", log.GetLevel().String()) - - log.Debug().Interface("session", session).Msg("Decomposedfs: built session info") - - err = fs.um.RunInBaseScope(func() error { - // Create binary file in the upload folder with no content - // It will be used when determining the current offset of an upload - err := session.TouchBin() - if err != nil { - return err - } - - return session.Persist(ctx) - }) - if err != nil { - return nil, err - } - metrics.UploadSessionsInitiated.Inc() - - if uploadLength == 0 { - // Directly finish this upload - err = session.FinishUploadDecomposed(ctx) - if err != nil { - return nil, err - } - } - - return map[string]string{ - "simple": session.ID(), - "tus": session.ID(), - }, nil -} - -// MarkProcessing toggles a processing flag on the resource. -func (fs *Decomposedfs) MarkProcessing(ctx context.Context, ref *provider.Reference, processing bool, sessionID string) error { - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - return err - } - if !n.Exists { - return errtypes.NotFound(ref.String()) - } - - // Early lock, so MarkProcessing is atomic. - f, err := lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return err - } - defer func() { - if cerr := f.Close(); cerr != nil { - appctx.GetLogger(ctx).Error().Err(cerr).Str("nodeid", n.ID).Msg("could not close mark-processing lock") - } - }() - - // Evict the node's in-process xattr cache so IsProcessing reads from disk while we hold the lock. - n.ResetXattrsCache() - - if !processing { - if !n.IsProcessing(ctx) { - return nil - } - id, _ := n.ProcessingID(ctx) - if id != sessionID { - return nil // owned by a different session, do not clear - } - return n.RemoveXattr(ctx, prefixes.StatusPrefix, false) - } - - if n.IsProcessing(ctx) { - return errtypes.ResourceProcessing(ref.String()) - } - return n.SetXattrsWithContext(ctx, node.Attributes{ - prefixes.StatusPrefix: []byte(node.ProcessingStatus + sessionID), - }, false) // acquireLock=false, because outer lock already held -} - -// CommitUpload writes the staged bytes from source to the resource at ref. -// sessionID is used to identify the correct blob slot prepared before postprocessing. -// Caller owns source.Body and must close it after CommitUpload returns. -func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source storage.UploadSource) error { - if source.Body == nil { - return errtypes.BadRequest("Decomposedfs: source body is nil") - } - if sessionID == "" { - return errtypes.BadRequest("Decomposedfs: sessionID is empty") - } - - n, err := fs.lu.NodeFromResource(ctx, ref) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("CommitUpload: unexpected NodeFromResource failure") - return errtypes.InternalError("CommitUpload: node lookup failed unexpectedly") - } - if !n.Exists { - return errtypes.NotFound(ref.String()) - } - - blobNode := node.New(n.SpaceID, n.ID, "", "", source.Length, sessionID, - provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu) - - if err := fs.tp.WriteBlobFromReader(blobNode, source.Body, source.Length); err != nil { - if derr := fs.tp.DeleteBlob(blobNode); derr != nil { - appctx.GetLogger(ctx).Error().Err(derr).Str("nodeid", n.ID).Str("blobid", sessionID).Msg("could not clean up orphaned blob after failed write") - } - return errors.Wrap(err, "Decomposedfs: failed to write blob") - } - - now := time.Now() - if p, err := n.Parent(ctx); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not read parent for etag propagation") - } else { - _ = p.SetTMTime(ctx, &now) - if err := fs.tp.Propagate(ctx, p, 0); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not propagate etag change") - } - } - - return nil -} - -// UseIn tells the tus upload middleware which extensions it supports. -func (fs *Decomposedfs) UseIn(composer *tusd.StoreComposer) { - composer.UseCore(fs) - composer.UseTerminater(fs) - composer.UseConcater(fs) - composer.UseLengthDeferrer(fs) -} - -// To implement the core tus.io protocol as specified in https://tus.io/protocols/resumable-upload.html#core-protocol -// - the storage needs to implement NewUpload and GetUpload -// - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload - -// NewUpload returns a new tus Upload instance -func (fs *Decomposedfs) NewUpload(ctx context.Context, info tusd.FileInfo) (tusd.Upload, error) { - return nil, fmt.Errorf("not implemented, use InitiateUpload on the CS3 API to start a new upload") -} - -// GetUpload returns the Upload for the given upload id -func (fs *Decomposedfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { - var ul tusd.Upload - var err error - _ = fs.um.RunInBaseScope(func() error { - ul, err = fs.sessionStore.Get(ctx, id) - return nil - }) - return ul, err -} - -// ListUploadSessions returns the upload sessions for the given filter -func (fs *Decomposedfs) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) { - var sessions []*upload.OcisSession - if filter.ID != nil && *filter.ID != "" { - session, err := fs.sessionStore.Get(ctx, *filter.ID) - if err != nil { - return nil, err - } - sessions = []*upload.OcisSession{session} - } else { - var err error - sessions, err = fs.sessionStore.List(ctx) - if err != nil { - return nil, err - } - } - filteredSessions := []storage.UploadSession{} - now := time.Now() - for _, session := range sessions { - if filter.Processing != nil && *filter.Processing != session.IsProcessing() { - continue - } - if filter.Expired != nil { - if *filter.Expired { - if now.Before(session.Expires()) { - continue - } - } else { - if now.After(session.Expires()) { - continue - } - } - } - if filter.HasVirus != nil { - sr, _ := session.ScanData() - infected := sr != "" - if *filter.HasVirus != infected { - continue - } - } - filteredSessions = append(filteredSessions, session) - } - return filteredSessions, nil -} - -// AsTerminatableUpload returns a TerminatableUpload -// To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination -// the storage needs to implement AsTerminatableUpload -func (fs *Decomposedfs) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return up.(*upload.OcisSession) -} - -// AsLengthDeclarableUpload returns a LengthDeclarableUpload -// To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation -// the storage needs to implement AsLengthDeclarableUpload -func (fs *Decomposedfs) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return up.(*upload.OcisSession) -} - -// AsConcatableUpload returns a ConcatableUpload -// To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation -// the storage needs to implement AsConcatableUpload -func (fs *Decomposedfs) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return up.(*upload.OcisSession) -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/session.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/session.go deleted file mode 100644 index 22ff4d8995..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/session.go +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2018-2023 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package upload - -import ( - "context" - "encoding/json" - "os" - "path/filepath" - "strconv" - "time" - - "github.com/google/renameio/v2" - tusd "github.com/tus/tusd/v2/pkg/handler" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -// OcisSession extends tus upload lifecycle with postprocessing steps. -type OcisSession struct { - store OcisStore - // for now, we keep the json files in the uploads folder - info tusd.FileInfo -} - -// Context returns a context with the user, logger and lockid used when initiating the upload session -func (s *OcisSession) Context(ctx context.Context) context.Context { // restore logger from file info - sub := s.store.log.With().Int("pid", os.Getpid()).Logger() - ctx = appctx.WithLogger(ctx, &sub) - ctx = ctxpkg.ContextSetLockID(ctx, s.lockID()) - ctx = ctxpkg.ContextSetUser(ctx, s.executantUser()) - return ctxpkg.ContextSetInitiator(ctx, s.InitiatorID()) -} - -func (s *OcisSession) lockID() string { - return s.info.MetaData["lockid"] -} -func (s *OcisSession) executantUser() *userpb.User { - var o *typespb.Opaque - _ = json.Unmarshal([]byte(s.info.Storage["UserOpaque"]), &o) - return &userpb.User{ - Id: &userpb.UserId{ - Type: userpb.UserType(userpb.UserType_value[s.info.Storage["UserType"]]), - Idp: s.info.Storage["Idp"], - OpaqueId: s.info.Storage["UserId"], - }, - Username: s.info.Storage["UserName"], - DisplayName: s.info.Storage["UserDisplayName"], - Opaque: o, - } -} - -// Purge deletes the upload session metadata and written binary data -func (s *OcisSession) Purge(ctx context.Context) { - _, span := tracer.Start(ctx, "Purge") - defer span.End() - s.Cleanup(true, true, true, true) -} - -// TouchBin creates a file to contain the binary data. It's size will be used to keep track of the tus upload offset. -func (s *OcisSession) TouchBin() error { - file, err := os.OpenFile(s.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm) - if err != nil { - return err - } - return file.Close() -} - -// Persist writes the upload session metadata to disk -// events can update the scan outcome and the finished event might read an empty file because of race conditions -// so we need to lock the file while writing and use atomic writes -func (s *OcisSession) Persist(ctx context.Context) error { - _, span := tracer.Start(ctx, "Persist") - defer span.End() - infoPath := s.infoPath() - // create folder structure (if needed) - if err := os.MkdirAll(filepath.Dir(infoPath), 0700); err != nil { - return err - } - - var d []byte - d, err := json.Marshal(s.info) - if err != nil { - return err - } - return renameio.WriteFile(infoPath, d, 0600) -} - -// ToFileInfo returns tus compatible FileInfo so the tus handler can access the upload offset -func (s *OcisSession) ToFileInfo() tusd.FileInfo { - return s.info -} - -// ProviderID returns the provider id -func (s *OcisSession) ProviderID() string { - return s.info.MetaData["providerID"] -} - -// SpaceID returns the space id -func (s *OcisSession) SpaceID() string { - return s.info.Storage["SpaceRoot"] -} - -// NodeID returns the node id -func (s *OcisSession) NodeID() string { - return s.info.Storage["NodeId"] -} - -// NodeParentID returns the nodes parent id -func (s *OcisSession) NodeParentID() string { - return s.info.Storage["NodeParentId"] -} - -// NodeExists returns wether or not the node existed during InitiateUpload. -// FIXME If two requests try to write the same file they both will store a new -// random node id in the session and try to initialize a new node when -// finishing the upload. The second request will fail with an already exists -// error when trying to create the symlink for the node in the parent directory. -// A node should be created as part of InitiateUpload. When listing a directory -// we can decide if we want to skip the entry, or expose uploed progress -// information. But that is a bigger change and might involve client work. -func (s *OcisSession) NodeExists() bool { - return s.info.Storage["NodeExists"] == "true" -} - -// HeaderIfMatch returns the if-match header for the upload session -func (s *OcisSession) HeaderIfMatch() string { - return s.info.MetaData["if-match"] -} - -// HeaderIfNoneMatch returns the if-none-match header for the upload session -func (s *OcisSession) HeaderIfNoneMatch() string { - return s.info.MetaData["if-none-match"] -} - -// HeaderIfUnmodifiedSince returns the if-unmodified-since header for the upload session -func (s *OcisSession) HeaderIfUnmodifiedSince() string { - return s.info.MetaData["if-unmodified-since"] -} - -// Node returns the node for the session -func (s *OcisSession) Node(ctx context.Context) (*node.Node, error) { - return node.ReadNode(ctx, s.store.lu, s.SpaceID(), s.info.Storage["NodeId"], false, nil, true) -} - -// ID returns the upload session id -func (s *OcisSession) ID() string { - return s.info.ID -} - -// Filename returns the name of the node which is not the same as the name af the file being uploaded for legacy chunked uploads -func (s *OcisSession) Filename() string { - return s.info.Storage["NodeName"] -} - -// Chunk returns the chunk name when a legacy chunked upload was started -func (s *OcisSession) Chunk() string { - return s.info.Storage["Chunk"] -} - -// SetMetadata is used to fill the upload metadata that will be exposed to the end user -func (s *OcisSession) SetMetadata(key, value string) { - s.info.MetaData[key] = value -} - -// SetStorageValue is used to set metadata only relevant for the upload session implementation -func (s *OcisSession) SetStorageValue(key, value string) { - s.info.Storage[key] = value -} - -// SetSize will set the upload size of the underlying tus info. -func (s *OcisSession) SetSize(size int64) { - s.info.Size = size -} - -// SetSizeIsDeferred is uset to change the SizeIsDeferred property of the underlying tus info. -func (s *OcisSession) SetSizeIsDeferred(value bool) { - s.info.SizeIsDeferred = value -} - -// Dir returns the directory to which the upload is made -// TODO get rid of Dir(), whoever consumes the reference should be able to deal -// with a relative reference. -// Dir is only used to: -// - fill the Path property when emitting the UploadReady event after -// postprocessing finished. I wonder why the UploadReady contains a finished -// flag ... maybe multiple distinct events would make more sense. -// - build the reference that is passed to the FileUploaded event in the -// UploadFinishedFunc callback passed to the Upload call used for simple -// datatx put requests -// -// AFAICT only search and audit services consume the path. -// - search needs to index from the root anyway. And it only needs the most -// recent path to put it in the index. So it should already be able to deal -// with an id based reference. -// - audit on the other hand needs to log events with the path at the state of -// the event ... so it does need the full path. -// -// I think we can safely determine the path later, right before emitting the -// event. And maybe make it configurable, because only audit needs it, anyway. -func (s *OcisSession) Dir() string { - return s.info.Storage["Dir"] -} - -// Size returns the upload size -func (s *OcisSession) Size() int64 { - return s.info.Size -} - -// SizeDiff returns the size diff that was calculated after postprocessing -func (s *OcisSession) SizeDiff() int64 { - sizeDiff, _ := strconv.ParseInt(s.info.MetaData["sizeDiff"], 10, 64) - return sizeDiff -} - -// Reference returns a reference that can be used to access the uploaded resource -func (s *OcisSession) Reference() provider.Reference { - return provider.Reference{ - ResourceId: &provider.ResourceId{ - StorageId: s.info.MetaData["providerID"], - SpaceId: s.info.Storage["SpaceRoot"], - OpaqueId: s.info.Storage["NodeId"], - }, - // Path is not used - } -} - -// Executant returns the id of the user that initiated the upload session -func (s *OcisSession) Executant() userpb.UserId { - return userpb.UserId{ - Type: userpb.UserType(userpb.UserType_value[s.info.Storage["UserType"]]), - Idp: s.info.Storage["Idp"], - OpaqueId: s.info.Storage["UserId"], - } -} - -// SetExecutant is used to remember the user that initiated the upload session -func (s *OcisSession) SetExecutant(u *userpb.User) { - s.info.Storage["Idp"] = u.GetId().GetIdp() - s.info.Storage["UserId"] = u.GetId().GetOpaqueId() - s.info.Storage["UserType"] = utils.UserTypeToString(u.GetId().Type) - s.info.Storage["UserName"] = u.GetUsername() - s.info.Storage["UserDisplayName"] = u.GetDisplayName() - - b, _ := json.Marshal(u.GetOpaque()) - s.info.Storage["UserOpaque"] = string(b) -} - -// Offset returns the current upload offset -func (s *OcisSession) Offset() int64 { - return s.info.Offset -} - -// SpaceOwner returns the id of the space owner -func (s *OcisSession) SpaceOwner() *userpb.UserId { - return &userpb.UserId{ - // idp and type do not seem to be consumed and the node currently only stores the user id anyway - OpaqueId: s.info.Storage["SpaceOwnerOrManager"], - } -} - -// Expires returns the time the upload session expires -func (s *OcisSession) Expires() time.Time { - var t time.Time - if value, ok := s.info.MetaData["expires"]; ok { - t, _ = utils.MTimeToTime(value) - } - return t -} - -// MTime returns the mtime to use for the uploaded file -func (s *OcisSession) MTime() time.Time { - var t time.Time - if value, ok := s.info.MetaData["mtime"]; ok { - t, _ = utils.MTimeToTime(value) - } - return t -} - -// IsProcessing returns true if all bytes have been received. The session then has entered postprocessing state. -func (s *OcisSession) IsProcessing() bool { - // We might need a more sophisticated way to determine processing status soon - return s.info.Size == s.info.Offset && s.info.MetaData["scanResult"] == "" -} - -// binPath returns the path to the file storing the binary data. -func (s *OcisSession) binPath() string { - return filepath.Join(s.store.root, "uploads", s.info.ID) -} - -// infoPath returns the path to the .info file storing the file's info. -func (s *OcisSession) infoPath() string { - return sessionPath(s.store.root, s.info.ID) -} - -// InitiatorID returns the id of the initiating client -func (s *OcisSession) InitiatorID() string { - return s.info.MetaData["initiatorid"] -} - -// SetScanData sets virus scan data to the upload session -func (s *OcisSession) SetScanData(result string, date time.Time) { - s.info.MetaData["scanResult"] = result - s.info.MetaData["scanDate"] = date.Format(time.RFC3339) -} - -// ScanData returns the virus scan data -func (s *OcisSession) ScanData() (string, time.Time) { - date := s.info.MetaData["scanDate"] - if date == "" { - return "", time.Time{} - } - d, _ := time.Parse(time.RFC3339, date) - return s.info.MetaData["scanResult"], d -} - -func (s *OcisSession) SetStatus(status string) { - s.info.MetaData["status"] = status -} - -func (s *OcisSession) Status() string { - return s.info.MetaData["status"] -} - -func (s *OcisSession) SetStatusMessage(message string) { - s.info.MetaData["status_message"] = message -} - -func (s *OcisSession) StatusMessage() string { - return s.info.MetaData["status_message"] -} - -// sessionPath returns the path to the .info file storing the file's info. -func sessionPath(root, id string) string { - return filepath.Join(root, "uploads", id+".info") -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/store.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/store.go deleted file mode 100644 index 63b66ef076..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/store.go +++ /dev/null @@ -1,423 +0,0 @@ -// Copyright 2018-2022 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package upload - -import ( - "context" - "encoding/json" - "fmt" - iofs "io/fs" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "syscall" - "time" - - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/google/uuid" - "github.com/opencloud-eu/reva/v2/pkg/appctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper" - "github.com/pkg/errors" - "github.com/rogpeppe/go-internal/lockedfile" - "github.com/rs/zerolog" - tusd "github.com/tus/tusd/v2/pkg/handler" -) - -var _idRegexp = regexp.MustCompile(".*/([^/]+).info") - -// PermissionsChecker defines an interface for checking permissions on a Node -type PermissionsChecker interface { - AssemblePermissions(ctx context.Context, n *node.Node) (ap provider.ResourcePermissions, err error) -} - -// OcisStore manages upload sessions -type OcisStore struct { - fs storage.FS - lu node.PathLookup - tp node.Tree - um usermapper.Mapper - root string - pub events.Publisher - async bool - tknopts options.TokenOptions - disableVersioning bool - log *zerolog.Logger -} - -// NewSessionStore returns a new OcisStore -func NewSessionStore(fs storage.FS, aspects aspects.Aspects, root string, async bool, tknopts options.TokenOptions, log *zerolog.Logger) *OcisStore { - return &OcisStore{ - fs: fs, - lu: aspects.Lookup, - tp: aspects.Tree, - root: root, - pub: aspects.EventStream, - async: async, - tknopts: tknopts, - disableVersioning: aspects.DisableVersioning, - um: aspects.UserMapper, - log: log, - } -} - -// New returns a new upload session -func (store OcisStore) New(ctx context.Context) *OcisSession { - return &OcisSession{ - store: store, - info: tusd.FileInfo{ - ID: uuid.New().String(), - Storage: map[string]string{ - "Type": "OCISStore", - }, - MetaData: tusd.MetaData{}, - }, - } -} - -// List lists all upload sessions -func (store OcisStore) List(ctx context.Context) ([]*OcisSession, error) { - uploads := []*OcisSession{} - infoFiles, err := filepath.Glob(filepath.Join(store.root, "uploads", "*.info")) - if err != nil { - return nil, err - } - - for _, info := range infoFiles { - id := strings.TrimSuffix(filepath.Base(info), filepath.Ext(info)) - progress, err := store.Get(ctx, id) - if err != nil { - appctx.GetLogger(ctx).Error().Interface("path", info).Msg("Decomposedfs: could not getUploadSession") - continue - } - - uploads = append(uploads, progress) - } - return uploads, nil -} - -// Get returns the upload session for the given upload id -func (store OcisStore) Get(ctx context.Context, id string) (*OcisSession, error) { - sessionPath := sessionPath(store.root, id) - match := _idRegexp.FindStringSubmatch(sessionPath) - if len(match) < 2 { - return nil, fmt.Errorf("invalid upload path") - } - - session := OcisSession{ - store: store, - info: tusd.FileInfo{}, - } - data, err := os.ReadFile(sessionPath) - if err != nil { - // handle stale NFS file handles that can occur when the file is deleted betwenn the ATTR and FOPEN call of os.ReadFile - if pathErr, ok := err.(*os.PathError); ok && pathErr.Err == syscall.ESTALE { - appctx.GetLogger(ctx).Info().Str("session", id).Err(err).Msg("treating stale file handle as not found") - err = tusd.ErrNotFound - } - if errors.Is(err, iofs.ErrNotExist) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - - if err := json.Unmarshal(data, &session.info); err != nil { - return nil, err - } - - stat, err := os.Stat(session.binPath()) - if err != nil { - if os.IsNotExist(err) { - // Interpret os.ErrNotExist as 404 Not Found - err = tusd.ErrNotFound - } - return nil, err - } - - session.info.Offset = stat.Size() - - return &session, nil -} - -// Session is the interface used by the Cleanup call -type Session interface { - ID() string - Node(ctx context.Context) (*node.Node, error) - Context(ctx context.Context) context.Context - Cleanup(revertNodeMetadata, cleanBin, cleanInfo bool) -} - -// CreateNodeForUpload will create the target node for the Upload -// TODO move this to the node package as NodeFromUpload? -// should we in InitiateUpload create the node first? and then the upload? -func (store OcisStore) CreateNodeForUpload(ctx context.Context, session *OcisSession, initAttrs node.Attributes) (*node.Node, error) { - ctx, span := tracer.Start(session.Context(ctx), "CreateNodeForUpload") - defer span.End() - n := node.New( - session.SpaceID(), - session.NodeID(), - session.NodeParentID(), - session.Filename(), - session.Size(), - session.ID(), - provider.ResourceType_RESOURCE_TYPE_FILE, - nil, - store.lu, - ) - var err error - n.SpaceRoot, err = node.ReadNode(ctx, store.lu, session.SpaceID(), session.SpaceID(), false, nil, false) - if err != nil { - return nil, err - } - - // check lock - if err := n.CheckLock(ctx); err != nil { - return nil, err - } - - var unlock metadata.UnlockFunc - if session.NodeExists() { // TODO this is wrong. The node should be created when the upload starts, the revisions should be created independently of the node - // we do not need to propagate a change when a node is created, only when the upload is ready. - // that still creates problems for desktop clients because if another change causes propagation it will detects an empty file - // so the first upload has to point to the first revision with the expected size. The file cannot be downloaded, but it can be overwritten (which will create a new revision and make the node reflect the latest revision) - // any finished postprocessing will not affect the node metadata. - // *thinking* but then initializing an upload will lock the file until the upload has finished. That sucks. - // so we have to check if the node has been created meanwhile (well, only in case the upload does not know the nodeid ... or the NodeExists array that is checked by session.NodeExists()) - // FIXME look at the disk again to see if the file has been created in between, or just try initializing a new node and do the update existing node as a fallback. <- the latter! - - unlock, err = store.updateExistingNode(ctx, session, n, session.SpaceID(), uint64(session.Size())) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("failed to update existing node") - } - } else { - if c, ok := store.lu.(node.IDCacher); ok { - err := c.CacheID(ctx, n.SpaceID, n.ID, filepath.Join(n.ParentPath(), n.Name)) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Msg("failed to cache id") - } - } - - unlock, err = store.tp.InitNewNode(ctx, n, uint64(session.Size())) - if err != nil { - appctx.GetLogger(ctx).Error().Str("path", n.InternalPath()).Err(err).Msg("failed to init new node") - } - session.info.MetaData["sizeDiff"] = strconv.FormatInt(session.Size(), 10) - } - defer func() { - if unlock == nil { - appctx.GetLogger(ctx).Info().Msg("did not get a unlockfunc, not unlocking") - return - } - - if err := unlock(); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Str("parentid", n.ParentID).Msg("could not close lock") - } - }() - if err != nil { - return nil, err - } - - // overwrite technical information - initAttrs.SetString(prefixes.IDAttr, n.ID) - initAttrs.SetInt64(prefixes.TypeAttr, int64(provider.ResourceType_RESOURCE_TYPE_FILE)) - initAttrs.SetString(prefixes.ParentidAttr, n.ParentID) - initAttrs.SetString(prefixes.NameAttr, n.Name) - initAttrs.SetString(prefixes.BlobIDAttr, n.BlobID) - initAttrs.SetInt64(prefixes.BlobsizeAttr, n.Blobsize) - initAttrs.SetString(prefixes.StatusPrefix, node.ProcessingStatus+session.ID()) - - // set mtime on the new node - mtime := time.Now() - if !session.MTime().IsZero() { - // overwrite mtime if requested - mtime = session.MTime() - } - err = store.lu.TimeManager().OverrideMtime(ctx, n, &initAttrs, mtime) - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: failed to set the mtime") - } - - // update node metadata with new blobid etc - err = n.SetXattrsWithContext(ctx, initAttrs, false) - if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: could not write metadata") - } - - err = store.um.RunInBaseScope(func() error { - return session.Persist(ctx) - }) - if err != nil { - return nil, err - } - - return n, nil -} - -func (store OcisStore) updateExistingNode(ctx context.Context, session *OcisSession, n *node.Node, spaceID string, fsize uint64) (metadata.UnlockFunc, error) { - _, span := tracer.Start(ctx, "updateExistingNode") - defer span.End() - targetPath := n.InternalPath() - - // write lock existing node before reading any metadata - f, err := lockedfile.OpenFile(store.lu.MetadataBackend().LockfilePath(targetPath), os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return nil, err - } - - unlock := func() error { - // NOTE: to prevent stale NFS file handles do not remove lock file! - return f.Close() - } - - old, _ := node.ReadNode(ctx, store.lu, spaceID, n.ID, false, nil, false) - if _, err := node.CheckQuota(ctx, n.SpaceRoot, true, uint64(old.Blobsize), fsize); err != nil { - return unlock, err - } - - oldNodeMtime, err := old.GetMTime(ctx) - if err != nil { - return unlock, err - } - oldNodeEtag, err := node.CalculateEtag(old.ID, oldNodeMtime) - if err != nil { - return unlock, err - } - - // When the if-match header was set we need to check if the - // etag still matches before finishing the upload. - if session.HeaderIfMatch() != "" && session.HeaderIfMatch() != oldNodeEtag { - return unlock, errtypes.Aborted("etag mismatch") - } - - // When the if-none-match header was set we need to check if any of the - // etags matches before finishing the upload. - if session.HeaderIfNoneMatch() != "" { - if session.HeaderIfNoneMatch() == "*" { - return unlock, errtypes.Aborted("etag mismatch, resource exists") - } - for _, ifNoneMatchTag := range strings.Split(session.HeaderIfNoneMatch(), ",") { - if ifNoneMatchTag == oldNodeEtag { - return unlock, errtypes.Aborted("etag mismatch") - } - } - } - - // When the if-unmodified-since header was set we need to check if the - // etag still matches before finishing the upload. - if session.HeaderIfUnmodifiedSince() != "" { - ifUnmodifiedSince, err := time.Parse(time.RFC3339Nano, session.HeaderIfUnmodifiedSince()) - if err != nil { - return unlock, errtypes.InternalError(fmt.Sprintf("failed to parse if-unmodified-since time: %s", err)) - } - - if oldNodeMtime.After(ifUnmodifiedSince) { - return unlock, errtypes.Aborted("if-unmodified-since mismatch") - } - } - - if !store.disableVersioning { - versionPath := session.store.lu.InternalPath(spaceID, n.ID+node.RevisionIDDelimiter+oldNodeMtime.UTC().Format(time.RFC3339Nano)) - - // create version node - _, err := os.OpenFile(versionPath, os.O_CREATE|os.O_EXCL, 0600) - if err != nil { - if !errors.Is(err, os.ErrExist) { - return unlock, err - } - - // a revision with this mtime does already exist. - // If the blobs are the same we can just delete the old one - if err := validateChecksums(ctx, old, session, versionPath); err != nil { - return unlock, err - } - - // delete old blob - bID, _, err := session.store.lu.ReadBlobIDAndSizeAttr(ctx, versionPath, nil) - if err != nil { - return unlock, err - } - if err := session.store.tp.DeleteBlob(&node.Node{BlobID: bID, SpaceID: n.SpaceID}); err != nil { - return unlock, err - } - - // clean revision file - span.AddEvent("os.Create") - if _, err := os.Create(versionPath); err != nil { - return unlock, err - } - } - - // copy blob metadata to version node - if err := store.lu.CopyMetadataWithSourceLock(ctx, targetPath, versionPath, func(attributeName string, value []byte) (newValue []byte, copy bool) { - return value, strings.HasPrefix(attributeName, prefixes.ChecksumPrefix) || - attributeName == prefixes.TypeAttr || - attributeName == prefixes.BlobIDAttr || - attributeName == prefixes.BlobsizeAttr || - attributeName == prefixes.MTimeAttr - }, f, true); err != nil { - return unlock, err - } - session.info.MetaData["versionsPath"] = versionPath - // keep mtime from previous version - span.AddEvent("os.Chtimes") - if err := os.Chtimes(session.info.MetaData["versionsPath"], oldNodeMtime, oldNodeMtime); err != nil { - return unlock, errtypes.InternalError(fmt.Sprintf("failed to change mtime of version node: %s", err)) - } - } - - session.info.MetaData["sizeDiff"] = strconv.FormatInt((int64(fsize) - old.Blobsize), 10) - - return unlock, nil -} - -func validateChecksums(ctx context.Context, n *node.Node, session *OcisSession, versionPath string) error { - for _, t := range []string{"md5", "sha1", "adler32"} { - key := prefixes.ChecksumPrefix + t - - checksum, err := n.Xattr(ctx, key) - if err != nil { - return err - } - - revisionChecksum, err := session.store.lu.MetadataBackend().Get(ctx, versionPath, key) - if err != nil { - return err - } - - if string(checksum) == "" || string(revisionChecksum) == "" { - return errors.New("checksum not found") - } - - if string(checksum) != string(revisionChecksum) { - return errors.New("checksum mismatch") - } - } - - return nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/upload.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/upload.go deleted file mode 100644 index b6eb62f71f..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload/upload.go +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright 2018-2022 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package upload - -import ( - "context" - "encoding/hex" - "fmt" - "hash" - "io" - "io/fs" - "net/http" - "os" - "strconv" - "strings" - "time" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/golang-jwt/jwt/v5" - "github.com/pkg/errors" - tusd "github.com/tus/tusd/v2/pkg/handler" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/trace" - - "github.com/opencloud-eu/reva/v2/pkg/appctx" - ctxpkg "github.com/opencloud-eu/reva/v2/pkg/ctx" - "github.com/opencloud-eu/reva/v2/pkg/errtypes" - "github.com/opencloud-eu/reva/v2/pkg/events" - "github.com/opencloud-eu/reva/v2/pkg/rhttp/datatx/metrics" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node" - "github.com/opencloud-eu/reva/v2/pkg/utils" -) - -var ( - tracer trace.Tracer - ErrAlreadyExists = tusd.NewError("ERR_ALREADY_EXISTS", "file already exists", http.StatusConflict) - defaultFilePerm = os.FileMode(0664) -) - -func init() { - tracer = otel.Tracer("github.com/cs3org/reva/pkg/storage/utils/decomposedfs/upload") -} - -// WriteChunk writes the stream from the reader to the given offset of the upload -func (session *OcisSession) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { - ctx, span := tracer.Start(session.Context(ctx), "WriteChunk") - defer span.End() - _, subspan := tracer.Start(ctx, "os.OpenFile") - file, err := os.OpenFile(session.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - subspan.End() - - log := appctx.GetLogger(ctx) - if err != nil { - log.Error().Err(err).Msg("WriteChunk: error opening upload file") - return 0, err - } - defer file.Close() - - // calculate cheksum here? needed for the TUS checksum extension. https://tus.io/protocols/resumable-upload.html#checksum - // TODO but how do we get the `Upload-Checksum`? WriteChunk() only has a context, offset and the reader ... - // It is sent with the PATCH request, well or in the POST when the creation-with-upload extension is used - // but the tus handler uses a context.Background() so we cannot really check the header and put it in the context ... - _, subspan = tracer.Start(ctx, "io.Copy") - n, err := io.Copy(file, src) - subspan.End() - - // If the HTTP PATCH request gets interrupted in the middle (e.g. because - // the user wants to pause the upload), Go's net/http returns an io.ErrUnexpectedEOF. - // However, for the ocis driver it's not important whether the stream has ended - // on purpose or accidentally. - if err != nil && err != io.ErrUnexpectedEOF { - log.Error().Err(err).Msg("WriteChunk: error copying data to upload file") - return n, err - } - - // update upload.Session.Offset so subsequent code flow can use it. - // No need to persist the session as the offset is determined by stating the blob in the GetUpload / ReadSession codepath. - // The session offset is written to disk in FinishUpload - session.info.Offset += n - return n, nil -} - -// GetInfo returns the FileInfo -func (session *OcisSession) GetInfo(_ context.Context) (tusd.FileInfo, error) { - return session.ToFileInfo(), nil -} - -// GetReader returns an io.Reader for the upload -func (session *OcisSession) GetReader(ctx context.Context) (io.ReadCloser, error) { - _, span := tracer.Start(session.Context(ctx), "GetReader") - defer span.End() - return os.Open(session.binPath()) -} - -// FinishUpload finishes an upload and moves the file to the internal destination -// implements tusd.DataStore interface -// returns tusd errors -func (session *OcisSession) FinishUpload(ctx context.Context) error { - err := session.FinishUploadDecomposed(ctx) - - if err != nil { - // this is part of the tusd integration and we might be able to - // log the error in another place - log := appctx.GetLogger(ctx) - log.Error().Err(err).Msg("failed to finish upload") - } - - // we need to return a tusd error here to make the tusd handler return the correct status code - switch err.(type) { - case errtypes.AlreadyExists: - return tusd.NewError("ERR_ALREADY_EXISTS", err.Error(), http.StatusConflict) - case errtypes.Aborted: - return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusPreconditionFailed) - case errtypes.InsufficientStorage: - return tusd.NewError("ERR_INSUFFICIENT_STORAGE", err.Error(), http.StatusInsufficientStorage) - default: - return err - } -} - -// FinishUploadDecomposed finishes an upload and moves the file to the internal destination -// retures errtypes errors -func (session *OcisSession) FinishUploadDecomposed(ctx context.Context) error { - ctx, span := tracer.Start(session.Context(ctx), "FinishUpload") - defer span.End() - log := appctx.GetLogger(ctx) - - ctx = ctxpkg.ContextSetInitiator(ctx, session.InitiatorID()) - - sha1h, md5h, adler32h, err := node.CalculateChecksums(ctx, session.binPath()) - if err != nil { - return err - } - - // compare if they match the sent checksum - // TODO the tus checksum extension would do this on every chunk, but I currently don't see an easy way to pass in the requested checksum. for now we do it in FinishUpload which is also called for chunked uploads - if session.info.MetaData["checksum"] != "" { - var err error - parts := strings.SplitN(session.info.MetaData["checksum"], " ", 2) - if len(parts) != 2 { - return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'") - } - switch parts[0] { - case "sha1": - err = checkHash(parts[1], sha1h) - case "md5": - err = checkHash(parts[1], md5h) - case "adler32": - err = checkHash(parts[1], adler32h) - default: - err = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0]) - } - if err != nil { - session.Cleanup(false, true, true, false) - return err - } - } - - // update checksums - attrs := node.Attributes{ - prefixes.ChecksumPrefix + "sha1": sha1h.Sum(nil), - prefixes.ChecksumPrefix + "md5": md5h.Sum(nil), - prefixes.ChecksumPrefix + "adler32": adler32h.Sum(nil), - } - - // At this point we scope by the space to create the final file in the final location - if session.store.um != nil && session.info.Storage["SpaceGid"] != "" { - gid, err := strconv.Atoi(session.info.Storage["SpaceGid"]) - if err != nil { - return errors.Wrap(err, "failed to parse space gid") - } - - unscope, err := session.store.um.ScopeUserByIds(-1, gid) - if err != nil { - return errors.Wrap(err, "failed to scope user") - } - if unscope != nil { - defer func() { _ = unscope() }() - } - } - - n, err := session.store.CreateNodeForUpload(ctx, session, attrs) - if err != nil { - return err - } - // increase the processing counter for every started processing - // will be decreased in Cleanup() - metrics.UploadProcessing.Inc() - metrics.UploadSessionsBytesReceived.Inc() - - if session.store.pub != nil && session.info.Size > 0 { - u, _ := ctxpkg.ContextGetUser(ctx) - s, err := session.URL(ctx) - if err != nil { - return err - } - - var iu *userpb.User - if utils.ExistsInOpaque(u.Opaque, "impersonating-user") { - iu = &userpb.User{} - if err := utils.ReadJSONFromOpaque(u.Opaque, "impersonating-user", iu); err != nil { - return err - } - } - - if err := events.Publish(ctx, session.store.pub, events.BytesReceived{ - UploadID: session.ID(), - URL: s, - SpaceOwner: n.SpaceOwnerOrManager(session.Context(ctx)), - ExecutingUser: u, - ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID}, - Filename: session.Filename(), - Filesize: uint64(session.Size()), - ImpersonatingUser: iu, - }); err != nil { - return err - } - } - - // if the upload is synchronous or the upload is empty, finalize it now - // for 0-byte uploads we take a shortcut and finalize isn't called elsewhere - if !session.store.async || session.info.Size == 0 { - // handle postprocessing synchronously - err = session.Finalize(ctx) - session.Cleanup(err != nil, true, true, true) - if err != nil { - log.Error().Err(err).Msg("failed to upload") - return err - } - metrics.UploadSessionsFinalized.Inc() - } - - return session.store.tp.Propagate(ctx, n, session.SizeDiff()) -} - -// Terminate terminates the upload -func (session *OcisSession) Terminate(_ context.Context) error { - session.Cleanup(true, true, true, true) - return nil -} - -// DeclareLength updates the upload length information -func (session *OcisSession) DeclareLength(ctx context.Context, length int64) error { - session.info.Size = length - session.info.SizeIsDeferred = false - return session.store.um.RunInBaseScope(func() error { - return session.Persist(session.Context(ctx)) - }) -} - -// ConcatUploads concatenates multiple uploads -func (session *OcisSession) ConcatUploads(_ context.Context, uploads []tusd.Upload) (err error) { - file, err := os.OpenFile(session.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm) - if err != nil { - return err - } - defer file.Close() - - for _, partialUpload := range uploads { - fileUpload := partialUpload.(*OcisSession) - - src, err := os.Open(fileUpload.binPath()) - if err != nil { - return err - } - defer src.Close() - - if _, err := io.Copy(file, src); err != nil { - return err - } - } - - return -} - -// Finalize finalizes the upload (eg moves the file to the internal destination) -func (session *OcisSession) Finalize(ctx context.Context) (err error) { - ctx, span := tracer.Start(session.Context(ctx), "Finalize") - defer span.End() - - revisionNode := node.New(session.SpaceID(), session.NodeID(), "", "", session.Size(), session.ID(), - provider.ResourceType_RESOURCE_TYPE_FILE, session.SpaceOwner(), session.store.lu) - - // upload the data to the blobstore - _, subspan := tracer.Start(ctx, "WriteBlob") - err = session.store.tp.WriteBlob(revisionNode, session.binPath()) - subspan.End() - if err != nil { - return errors.Wrap(err, "failed to upload file to blobstore") - } - - return nil -} - -func checkHash(expected string, h hash.Hash) error { - hash := hex.EncodeToString(h.Sum(nil)) - if expected != hash { - return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %x", expected, hash)) - } - return nil -} - -// cleanup cleans up after the upload is finished -func (session *OcisSession) Cleanup(revertNodeMetadata, cleanBin, cleanInfo, unmarkPostprocessing bool) { - ctx := session.Context(context.Background()) - - if cleanBin { - if err := os.Remove(session.binPath()); err != nil && !errors.Is(err, fs.ErrNotExist) { - appctx.GetLogger(ctx).Error().Str("path", session.binPath()).Err(err).Msg("removing upload failed") - } - } - - if cleanInfo { - if err := os.Remove(session.infoPath()); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("session", session.ID()).Msg("removing upload info failed") - } - } - - if revertNodeMetadata { - n, err := session.Node(ctx) - if err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("sessionid", session.ID()).Msg("reading node for session failed") - return - } - - versionID := strings.TrimPrefix(session.info.MetaData["versionsPath"], n.InternalPath()+node.RevisionIDDelimiter) - if session.NodeExists() && versionID != "" { - if err := n.RevertUpload(ctx, versionID); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Msg("reverting node metadata failed") - return - } - } else { - // 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 { - appctx.GetLogger(ctx).Error().Err(err).Str("spaceid", n.SpaceID).Str("nodeid", n.ID).Str("uploadid", session.ID()).Msg("reading processingid for session failed") - } - if latestSession == session.ID() { - // actually delete the node - if err := n.Purge(ctx); err != nil { - appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", n.InternalPath()).Msg("purging node failed") - return - } - } - // FIXME else if the upload has become a revision, delete the revision, or if it is the last one, delete the node - } - } - - if unmarkPostprocessing { - n, err := session.Node(ctx) - if err != nil { - appctx.GetLogger(ctx).Info().Str("session", session.ID()).Err(err).Msg("could not read node") - return - } - // FIXME: after cleanup the node might already be deleted ... - if n != nil { // node can be nil when there was an error before it was created (eg. checksum-mismatch) - if err := n.UnmarkProcessing(ctx, session.ID()); err != nil { - appctx.GetLogger(ctx).Info().Str("path", n.InternalPath()).Err(err).Msg("unmarking processing failed") - } - } - } -} - -// URL returns a url to download an upload -func (session *OcisSession) URL(_ context.Context) (string, error) { - u := joinurl(session.store.tknopts.DownloadEndpoint, "tus/", session.ID()) - if session.store.tknopts.DataGatewayEndpoint == "" { - return u, nil - } - - // we need to create a token - type transferClaims struct { - jwt.RegisteredClaims - Target string `json:"target"` - } - - ttl := time.Duration(session.store.tknopts.TransferExpires) * time.Second - claims := transferClaims{ - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)), - Audience: jwt.ClaimStrings{"reva"}, - IssuedAt: jwt.NewNumericDate(time.Now()), - }, - Target: u, - } - - t := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims) - - tkn, err := t.SignedString([]byte(session.store.tknopts.TransferSharedSecret)) - if err != nil { - return "", errors.Wrapf(err, "error signing token with claims %+v", claims) - } - - return joinurl(session.store.tknopts.DataGatewayEndpoint, tkn), nil -} - -// replace with url.JoinPath after switching to go1.19 -func joinurl(paths ...string) string { - var s strings.Builder - l := len(paths) - for i, p := range paths { - s.WriteString(p) - if !strings.HasSuffix(p, "/") && i != l-1 { - s.WriteString("/") - } - } - - return s.String() -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper.go deleted file mode 100644 index c5a51376d9..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package usermapper - -import ( - "context" -) - -// Mapper is the interface that wraps the basic mapping methods -type Mapper interface { - RunInBaseScope(f func() error) error - ScopeBase() (func() error, error) - ScopeUser(ctx context.Context) (func() error, error) - ScopeUserByIds(uid, gid int) (func() error, error) -} - -// UnscopeFunc is a function that unscopes the current user -type UnscopeFunc func() error - -// NullMapper is a user mapper that does nothing -type NullMapper struct{} - -// RunInBaseScope runs the given function in the scope of the base user -func (nm *NullMapper) RunInBaseScope(f func() error) error { - return f() -} - -// ScopeBase returns to the base uid and gid returning a function that can be used to restore the previous scope -func (nm *NullMapper) ScopeBase() (func() error, error) { - return func() error { return nil }, nil -} - -// ScopeUser returns to the base uid and gid returning a function that can be used to restore the previous scope -func (nm *NullMapper) ScopeUser(ctx context.Context) (func() error, error) { - return func() error { return nil }, nil -} - -func (nm *NullMapper) ScopeUserByIds(uid, gid int) (func() error, error) { - return func() error { return nil }, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper_linux.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper_linux.go deleted file mode 100644 index e806f6c324..0000000000 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper/usermapper_linux.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2018-2021 CERN -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// In applying this license, CERN does not waive the privileges and immunities -// granted to it by virtue of its status as an Intergovernmental Organization -// or submit itself to any jurisdiction. - -package usermapper - -import ( - "context" - "fmt" - "os/user" - "runtime" - "strconv" - - "golang.org/x/sys/unix" - - revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" -) - -// UnixMapper is a user mapper that maps users to unix uids and gids -type UnixMapper struct { - baseUid int - baseGid int -} - -// New returns a new user mapper -func NewUnixMapper() *UnixMapper { - baseUid, _ := unix.SetfsuidRetUid(-1) - baseGid, _ := unix.SetfsgidRetGid(-1) - - return &UnixMapper{ - baseUid: baseUid, - baseGid: baseGid, - } -} - -// RunInUserScope runs the given function in the scope of the base user -func (um *UnixMapper) RunInBaseScope(f func() error) error { - unscope, err := um.ScopeBase() - if err != nil { - return err - } - defer func() { _ = unscope() }() - - return f() -} - -// ScopeBase returns to the base uid and gid returning a function that can be used to restore the previous scope -func (um *UnixMapper) ScopeBase() (func() error, error) { - return um.ScopeUserByIds(-1, um.baseGid) -} - -// ScopeUser returns to the base uid and gid returning a function that can be used to restore the previous scope -func (um *UnixMapper) ScopeUser(ctx context.Context) (func() error, error) { - u := revactx.ContextMustGetUser(ctx) - - uid, gid, err := um.mapUser(u.Username) - if err != nil { - return nil, err - } - return um.ScopeUserByIds(uid, gid) -} - -// ScopeUserByIds scopes the current user to the given uid and gid returning a function that can be used to restore the previous scope -func (um *UnixMapper) ScopeUserByIds(uid, gid int) (func() error, error) { - runtime.LockOSThread() // Lock this Goroutine to the current OS thread - - var err error - var prevUid int - var prevGid int - if uid >= 0 { - prevUid, err = unix.SetfsuidRetUid(uid) - if err != nil { - return nil, err - } - if testUid, _ := unix.SetfsuidRetUid(-1); testUid != uid { - return nil, fmt.Errorf("failed to setfsuid to %d", uid) - } - } - if gid >= 0 { - prevGid, err = unix.SetfsgidRetGid(gid) - if err != nil { - return nil, err - } - if testGid, _ := unix.SetfsgidRetGid(-1); testGid != gid { - return nil, fmt.Errorf("failed to setfsgid to %d", gid) - } - } - - return func() error { - if uid >= 0 { - _ = unix.Setfsuid(prevUid) - } - if gid >= 0 { - _ = unix.Setfsgid(prevGid) - } - runtime.UnlockOSThread() - return nil - }, nil -} - -func (u *UnixMapper) mapUser(username string) (int, int, error) { - userDetails, err := user.Lookup(username) - if err != nil { - return 0, 0, err - } - - uid, err := strconv.Atoi(userDetails.Uid) - if err != nil { - return 0, 0, err - } - gid, err := strconv.Atoi(userDetails.Gid) - if err != nil { - return 0, 0, err - } - - return uid, gid, nil -} diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go index 05e8bec1b2..94ec157be2 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/storage/utils/middleware/middleware.go @@ -29,7 +29,6 @@ import ( "github.com/opencloud-eu/reva/v2/pkg/errtypes" "github.com/opencloud-eu/reva/v2/pkg/storage" - "github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload" "github.com/opencloud-eu/reva/v2/pkg/storagespace" ) @@ -94,21 +93,21 @@ func (f *FS) GetUpload(ctx context.Context, id string) (upload tusd.Upload, err // To implement the termination extension as specified in https://tus.io/protocols/resumable-upload.html#termination // the storage needs to implement AsTerminatableUpload func (f *FS) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload { - return up.(*upload.OcisSession) + return f.next.(tusd.TerminaterDataStore).AsTerminatableUpload(up) } // AsLengthDeclarableUpload returns a LengthDeclarableUpload // To implement the creation-defer-length extension as specified in https://tus.io/protocols/resumable-upload.html#creation // the storage needs to implement AsLengthDeclarableUpload func (f *FS) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload { - return up.(*upload.OcisSession) + return f.next.(tusd.LengthDeferrerDataStore).AsLengthDeclarableUpload(up) } // AsConcatableUpload returns a ConcatableUpload // To implement the concatenation extension as specified in https://tus.io/protocols/resumable-upload.html#concatenation // the storage needs to implement AsConcatableUpload func (f *FS) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload { - return up.(*upload.OcisSession) + return f.next.(tusd.ConcaterDataStore).AsConcatableUpload(up) } func (f *FS) GetHome(ctx context.Context) (string, error) { diff --git a/vendor/github.com/opencloud-eu/reva/v2/pkg/tags/tags.go b/vendor/github.com/opencloud-eu/reva/v2/pkg/tags/tags.go index 5113b3f8cf..7b0da1d3a5 100644 --- a/vendor/github.com/opencloud-eu/reva/v2/pkg/tags/tags.go +++ b/vendor/github.com/opencloud-eu/reva/v2/pkg/tags/tags.go @@ -69,6 +69,7 @@ func (t *Tags) Remove(s ...string) bool { } delete(t.exists, tag) + t.numtags-- removed = true } } diff --git a/vendor/modules.txt b/vendor/modules.txt index ad6f2d9ad0..f98a258621 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -458,8 +458,8 @@ github.com/go-acme/lego/v5/challenge # github.com/go-asn1-ber/asn1-ber v1.5.8 ## explicit; go 1.13 github.com/go-asn1-ber/asn1-ber -# github.com/go-chi/chi/v5 v5.3.2 -## explicit; go 1.23 +# github.com/go-chi/chi/v5 v5.4.0 +## explicit; go 1.24 github.com/go-chi/chi/v5 github.com/go-chi/chi/v5/middleware # github.com/go-chi/render v1.0.3 @@ -534,7 +534,7 @@ github.com/go-jose/go-jose/v3 github.com/go-jose/go-jose/v3/cipher github.com/go-jose/go-jose/v3/json github.com/go-jose/go-jose/v3/jwt -# github.com/go-jose/go-jose/v4 v4.1.5 +# github.com/go-jose/go-jose/v4 v4.1.6 ## explicit; go 1.24.0 github.com/go-jose/go-jose/v4 github.com/go-jose/go-jose/v4/cipher @@ -596,7 +596,7 @@ github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry ## explicit; go 1.12 github.com/go-ole/go-ole github.com/go-ole/go-ole/oleutil -# github.com/go-playground/locales v0.14.1 +# github.com/go-playground/locales v0.14.2 ## explicit; go 1.17 github.com/go-playground/locales github.com/go-playground/locales/currency @@ -604,8 +604,8 @@ github.com/go-playground/locales/en # github.com/go-playground/universal-translator v0.18.2 ## explicit; go 1.26 github.com/go-playground/universal-translator -# github.com/go-playground/validator/v10 v10.30.3 -## explicit; go 1.25.0 +# github.com/go-playground/validator/v10 v10.30.5 +## explicit; go 1.26.0 github.com/go-playground/validator/v10 github.com/go-playground/validator/v10/translations/en # github.com/go-redis/redis/v8 v8.11.5 @@ -889,8 +889,8 @@ github.com/kovidgoyal/imaging/prism/meta/webpmeta github.com/kovidgoyal/imaging/streams github.com/kovidgoyal/imaging/types github.com/kovidgoyal/imaging/webp -# github.com/leodido/go-urn v1.4.0 -## explicit; go 1.18 +# github.com/leodido/go-urn v1.5.0 +## explicit; go 1.24.0 github.com/leodido/go-urn github.com/leodido/go-urn/scim/schema # github.com/leonelquinteros/gotext v1.7.3-0.20260422134830-b012b4ccae69 @@ -1360,7 +1360,7 @@ github.com/opencloud-eu/icap-client # github.com/opencloud-eu/libre-graph-api-go v1.0.9-0.20261016073229-17ed3d5dd346 ## explicit; go 1.23 github.com/opencloud-eu/libre-graph-api-go -# github.com/opencloud-eu/reva/v2 v2.52.1 +# github.com/opencloud-eu/reva/v2 v2.52.2 ## explicit; go 1.26.0 github.com/opencloud-eu/reva/v2/cmd/revad/internal/grace github.com/opencloud-eu/reva/v2/cmd/revad/runtime @@ -1620,8 +1620,6 @@ github.com/opencloud-eu/reva/v2/pkg/storage/fs/loader github.com/opencloud-eu/reva/v2/pkg/storage/fs/local github.com/opencloud-eu/reva/v2/pkg/storage/fs/localhome github.com/opencloud-eu/reva/v2/pkg/storage/fs/nextcloud -github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis -github.com/opencloud-eu/reva/v2/pkg/storage/fs/ocis/blobstore github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql github.com/opencloud-eu/reva/v2/pkg/storage/fs/owncloudsql/filecache github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix @@ -1637,8 +1635,6 @@ github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/tree/assimilation github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/watcher github.com/opencloud-eu/reva/v2/pkg/storage/fs/posix/watcher/natswatcher github.com/opencloud-eu/reva/v2/pkg/storage/fs/registry -github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng -github.com/opencloud-eu/reva/v2/pkg/storage/fs/s3ng/blobstore github.com/opencloud-eu/reva/v2/pkg/storage/internal/goroutinelock github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs github.com/opencloud-eu/reva/v2/pkg/storage/pkg/decomposedfs/aspects @@ -1664,23 +1660,6 @@ github.com/opencloud-eu/reva/v2/pkg/storage/registry/static github.com/opencloud-eu/reva/v2/pkg/storage/utils/ace github.com/opencloud-eu/reva/v2/pkg/storage/utils/acl github.com/opencloud-eu/reva/v2/pkg/storage/utils/chunking -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/aspects -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/lookup -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/migrator -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/mtimesyncedcache -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/node -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/options -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/permissions -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/spaceidindex -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/timemanager -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/trashbin -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/tree/propagator -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/upload -github.com/opencloud-eu/reva/v2/pkg/storage/utils/decomposedfs/usermapper github.com/opencloud-eu/reva/v2/pkg/storage/utils/downloader github.com/opencloud-eu/reva/v2/pkg/storage/utils/eosfs github.com/opencloud-eu/reva/v2/pkg/storage/utils/filelocks From 9347da7c9c2fbda87cc876ebd26ec9f1564bddc9 Mon Sep 17 00:00:00 2001 From: OpenCloud Devops Date: Wed, 11 Nov 2026 16:41:10 +0100 Subject: [PATCH 16/19] =?UTF-8?q?=F0=9F=8E=89=20Release=209.1.0=20(#3841)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.0.1 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 * 🎉 Release 9.1.0 --- CHANGELOG.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 528009c585..1fd6d01ea0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,66 @@ # Changelog +## [9.1.0](https://github.com/opencloud-eu/opencloud/releases/tag/v9.1.0) - 2026-11-11 + +### ❤️ Thanks to all contributors! ❤️ + +@JammingBen, @RyoKusnadi, @aduffeck, @butonic, @dragotin, @dschmidt, @maki5, @micbar, @pascalwengerter, @rhafer, @v-scharf + +### 🔒 Security + +- fix(chore): upd deprecated chi RealIP middelware [[#3464](https://github.com/opencloud-eu/opencloud/pull/3464)] +- Add files for the Anthropic OSS-Scanner to run [[#3865](https://github.com/opencloud-eu/opencloud/pull/3865)] + +### 🐛 Bug Fixes + +- fix(proxy): allow blob: in media-src for motion and live photo playback [[#3896](https://github.com/opencloud-eu/opencloud/pull/3896)] +- fix(middleware): do not build the XFF middleware without trusted proxies [[#3937](https://github.com/opencloud-eu/opencloud/pull/3937)] +- fix(auth-guest): add missing guest link logout endpoint [[#3932](https://github.com/opencloud-eu/opencloud/pull/3932)] +- Remove redis-sentinel from store descriptions [[#3936](https://github.com/opencloud-eu/opencloud/pull/3936)] +- Bound the memory of bleve indexing [[#3900](https://github.com/opencloud-eu/opencloud/pull/3900)] +- fix: filter health checks from the pod ip [[#3914](https://github.com/opencloud-eu/opencloud/pull/3914)] +- fix: keep the health checks out of the access log [[#3908](https://github.com/opencloud-eu/opencloud/pull/3908)] +- fix(tracing): set the global text map propagator [[#3906](https://github.com/opencloud-eu/opencloud/pull/3906)] +- fix(proxy): answer 403 instead of 500 when the role claim is missing [[#3894](https://github.com/opencloud-eu/opencloud/pull/3894)] +- fix(webdav): stream announced types without a converter to the generator [[#3884](https://github.com/opencloud-eu/opencloud/pull/3884)] +- fix(search): normalize KQL path once [[#3516](https://github.com/opencloud-eu/opencloud/pull/3516)] +- fix(search): report rejected documents when indexing to OpenSearch [[#3142](https://github.com/opencloud-eu/opencloud/pull/3142)] +- fix(graph): expose allowedValues on driveItem children [[#3476](https://github.com/opencloud-eu/opencloud/pull/3476)] +- fix(search): index resources with out-of-range coordinates without a geopoint [[#3496](https://github.com/opencloud-eu/opencloud/pull/3496)] +- perf(search): skip unchanged facet keys when storing metadata [[#3682](https://github.com/opencloud-eu/opencloud/pull/3682)] + +### 📈 Enhancement + +- ability to disable http and/or event consumer for user log service [[#3285](https://github.com/opencloud-eu/opencloud/pull/3285)] + +### 📚 Documentation + +- docs: add audit logging ADR [[#3855](https://github.com/opencloud-eu/opencloud/pull/3855)] + +### 📦️ Dependencies + +- [full-ci] chore: bump reva to 2.52.2 [[#3955](https://github.com/opencloud-eu/opencloud/pull/3955)] +- [full-ci] chore: bump web to v8.2.2 [[#3962](https://github.com/opencloud-eu/opencloud/pull/3962)] +- [full-ci] chore: bump web to v8.2.2-beta.1 [[#3923](https://github.com/opencloud-eu/opencloud/pull/3923)] +- build(deps): bump github.com/prometheus/client_golang from 1.24.1 to 1.25.0 [[#3897](https://github.com/opencloud-eu/opencloud/pull/3897)] +- build(deps): bump github.com/nats-io/nats.go from 1.54.0 to 1.55.0 [[#3904](https://github.com/opencloud-eu/opencloud/pull/3904)] +- build(deps): bump github.com/kovidgoyal/imaging from 1.8.23 to 1.9.0 [[#3898](https://github.com/opencloud-eu/opencloud/pull/3898)] +- build(deps): bump google.golang.org/grpc from 1.84.0 to 1.85.0 [[#3885](https://github.com/opencloud-eu/opencloud/pull/3885)] +- build(deps): bump github.com/KimMachineGun/automemlimit from 1.0.0 to 1.0.1 [[#3886](https://github.com/opencloud-eu/opencloud/pull/3886)] +- build(deps): bump github.com/go-ldap/ldap/v3 from 3.4.14 to 3.4.15 [[#3887](https://github.com/opencloud-eu/opencloud/pull/3887)] +- build(deps): bump go.opentelemetry.io/otel/exporters/stdout/stdouttrace from 1.46.0 to 1.47.0 [[#3860](https://github.com/opencloud-eu/opencloud/pull/3860)] +- build(deps): bump golang.org/x/image from 0.46.0 to 0.47.0 [[#3861](https://github.com/opencloud-eu/opencloud/pull/3861)] +- build(deps): bump golang.org/x/net from 0.61.0 to 0.62.0 [[#3880](https://github.com/opencloud-eu/opencloud/pull/3880)] +- build(deps): bump golang.org/x/net from 0.59.0 to 0.61.0 [[#3851](https://github.com/opencloud-eu/opencloud/pull/3851)] +- build(deps): bump go.opentelemetry.io/otel/sdk from 1.46.0 to 1.47.0 [[#3850](https://github.com/opencloud-eu/opencloud/pull/3850)] +- build(deps): bump github.com/tidwall/gjson from 1.19.0 to 1.20.0 [[#3852](https://github.com/opencloud-eu/opencloud/pull/3852)] +- build(deps): bump github.com/davidbyttow/govips/v2 from 2.19.0 to 2.20.0 [[#3847](https://github.com/opencloud-eu/opencloud/pull/3847)] +- build(deps): bump github.com/onsi/ginkgo/v2 from 2.33.0 to 2.33.1 [[#3846](https://github.com/opencloud-eu/opencloud/pull/3846)] +- build(deps): bump github.com/shamaton/msgpack/v2 from 2.4.2 to 2.4.4 [[#3848](https://github.com/opencloud-eu/opencloud/pull/3848)] +- build(deps): bump github.com/grpc-ecosystem/grpc-gateway/v2 from 2.30.0 to 2.31.0 [[#3676](https://github.com/opencloud-eu/opencloud/pull/3676)] +- chore(deps): bump github.com/beevik/etree from 1.8.0 to 1.8.1 [[#3675](https://github.com/opencloud-eu/opencloud/pull/3675)] +- build(deps): bump github.com/davidbyttow/govips/v2 from 2.18.0 to 2.19.0 [[#3597](https://github.com/opencloud-eu/opencloud/pull/3597)] + ## [9.0.0](https://github.com/opencloud-eu/opencloud/releases/tag/v9.0.0) - 2026-10-27 ### ❤️ Thanks to all contributors! ❤️ From 0d969c3179efc0793ae452aee7967a8eec58441c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn=20Friedrich=20Dreyer?= Date: Mon, 9 Nov 2026 15:56:24 +0100 Subject: [PATCH 17/19] thumbnails: drop the enable_vips build flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The thumbnails service now always resizes in pure Go. Deployments that want more formats, webp output or an attention crop run a real imagor and point WEBDAV_THUMBNAILS_GENERATOR_URL at it. The built-in service stays as a minimal fallback that keeps working when imagor or libvips have to be taken out, for example during a security issue. Without cgo dependencies the docker images link statically again and no longer need the vips packages. The vips parity run in CI goes away, the regular test run already covers the pure Go build. The preview fixtures of the acceptance tests were rendered by libvips, so they are regenerated with the pure Go build. Text previews now lose their left edge: the 640x480 text canvas is filled into a square box and the pure Go build crops the centre, where libvips' attention crop kept the left side with the text. part of https://github.com/opencloud-eu/opencloud/issues/3912 Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Jörn Friedrich Dreyer --- .make/release.mk | 6 +- .vscode/launch.json | 3 - .woodpecker.star | 16 +- Dockerfile | 4 +- go.mod | 1 - go.sum | 2 - opencloud/Makefile | 3 - opencloud/docker/Dockerfile.linux.debug.amd64 | 2 +- opencloud/docker/Dockerfile.linux.debug.arm64 | 2 +- opencloud/docker/Dockerfile.multiarch | 5 +- services/thumbnails/README.md | 64 +- .../pkg/parity/build_imaging_test.go | 2 - .../thumbnails/pkg/parity/build_vips_test.go | 7 - .../thumbnails/pkg/service/http/v0/push.go | 7 +- .../pkg/service/http/v0/push_imaging.go | 26 +- .../pkg/service/http/v0/push_test.go | 2 +- .../pkg/service/http/v0/push_vips.go | 148 - .../pkg/service/http/v0/resizegif.go | 4 +- services/webdav/README.md | 2 +- services/webdav/pkg/generator/url.go | 4 +- .../coreApiWebdavPreviews/previews.feature | 6 +- tests/acceptance/fixtures/fill.jpg | Bin 967 -> 836 bytes tests/acceptance/fixtures/fit.jpg | Bin 804 -> 666 bytes tests/acceptance/fixtures/resize.jpg | Bin 944 -> 797 bytes .../acceptance/fixtures/text-file-fixture.jpg | Bin 68518 -> 63375 bytes tests/acceptance/fixtures/thumbnail.jpg | Bin 967 -> 836 bytes tests/acceptance/fixtures/unicode-fixture.jpg | Bin 10023 -> 18995 bytes .../github.com/davidbyttow/govips/v2/LICENSE | 24 - .../davidbyttow/govips/v2/vips/error.go | 39 - .../davidbyttow/govips/v2/vips/foreign.c | 628 -- .../davidbyttow/govips/v2/vips/foreign.go | 759 --- .../davidbyttow/govips/v2/vips/foreign.h | 155 - .../govips/v2/vips/gen_enum_extras.go | 139 - .../davidbyttow/govips/v2/vips/generate.go | 3 - .../davidbyttow/govips/v2/vips/generated.c | 5228 ----------------- .../davidbyttow/govips/v2/vips/generated.go | 5001 ---------------- .../davidbyttow/govips/v2/vips/generated.h | 1181 ---- .../davidbyttow/govips/v2/vips/govips.c | 27 - .../davidbyttow/govips/v2/vips/govips.go | 299 - .../davidbyttow/govips/v2/vips/govips.h | 26 - .../govips/v2/vips/icc_profiles.go | 724 --- .../davidbyttow/govips/v2/vips/image.c | 16 - .../davidbyttow/govips/v2/vips/image.go | 988 ---- .../davidbyttow/govips/v2/vips/image.h | 12 - .../davidbyttow/govips/v2/vips/image_color.go | 173 - .../govips/v2/vips/image_composite.go | 75 - .../govips/v2/vips/image_export.go | 439 -- .../davidbyttow/govips/v2/vips/image_icc.go | 108 - .../govips/v2/vips/image_metadata.go | 338 -- .../davidbyttow/govips/v2/vips/image_pixel.go | 393 -- .../govips/v2/vips/image_transform.go | 458 -- .../davidbyttow/govips/v2/vips/interpolate.go | 20 - .../davidbyttow/govips/v2/vips/lang.go | 62 - .../davidbyttow/govips/v2/vips/lang.h | 2 - .../davidbyttow/govips/v2/vips/logging.go | 98 - .../davidbyttow/govips/v2/vips/math.go | 57 - .../davidbyttow/govips/v2/vips/operations.c | 505 -- .../davidbyttow/govips/v2/vips/operations.go | 1083 ---- .../davidbyttow/govips/v2/vips/operations.h | 149 - .../davidbyttow/govips/v2/vips/stats.go | 56 - .../davidbyttow/govips/v2/vips/stream.c | 316 - .../davidbyttow/govips/v2/vips/stream.go | 842 --- .../davidbyttow/govips/v2/vips/stream.h | 85 - .../govips/v2/vips/test_resources.go | 6 - .../davidbyttow/govips/v2/vips/transcode.go | 104 - vendor/modules.txt | 3 - 66 files changed, 46 insertions(+), 20891 deletions(-) delete mode 100644 services/thumbnails/pkg/parity/build_vips_test.go delete mode 100644 services/thumbnails/pkg/service/http/v0/push_vips.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/LICENSE delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/error.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/foreign.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/foreign.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/foreign.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/gen_enum_extras.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/generate.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/generated.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/generated.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/generated.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/govips.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/govips.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/govips.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/icc_profiles.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_color.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_composite.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_export.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_icc.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_metadata.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_pixel.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/image_transform.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/interpolate.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/lang.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/lang.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/logging.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/math.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/operations.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/operations.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/operations.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/stats.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/stream.c delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/stream.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/stream.h delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/test_resources.go delete mode 100644 vendor/github.com/davidbyttow/govips/v2/vips/transcode.go diff --git a/.make/release.mk b/.make/release.mk index da0cf31c0d..67d50cc1ec 100644 --- a/.make/release.mk +++ b/.make/release.mk @@ -9,11 +9,7 @@ release-dirs: DOCKER_LDFLAGS += -X "$(OC_REPO)/pkg/config/defaults.BaseDataPathType=path" -X "$(OC_REPO)/pkg/config/defaults.BaseDataPathValue=/var/lib/opencloud" DOCKER_LDFLAGS += -X "$(OC_REPO)/pkg/config/defaults.BaseConfigPathType=path" -X "$(OC_REPO)/pkg/config/defaults.BaseConfigPathValue=/etc/opencloud" -# We can't link statically when vips is enabled but we still -# prefer static linking where possible -ifndef ENABLE_VIPS - DOCKER_LDFLAGS += -extldflags "-static" -endif +DOCKER_LDFLAGS += -extldflags "-static" release-linux-docker-amd64: release-dirs GOOS=linux \ diff --git a/.vscode/launch.json b/.vscode/launch.json index 2df4ec3068..250a748b1f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -19,9 +19,6 @@ "type": "go", "request": "launch", "mode": "debug", - "buildFlags": [ - // "-tags", "enable_vips" - ], "program": "${workspaceFolder}/opencloud/cmd/opencloud", "args": ["server"], "env": { diff --git a/.woodpecker.star b/.woodpecker.star index 522780e874..2afb5ceff4 100644 --- a/.woodpecker.star +++ b/.woodpecker.star @@ -804,20 +804,6 @@ def testOpencloud(ctx): "mv coverage.out unit.coverage.out", ], }, - { - # the only run that covers the resize code the official docker - # images ship - # FIXME: run it with the libvips those images ship, see issue 3746 - "name": "test-thumbnail-parity-vips", - "image": OC_CI_GOLANG, - "environment": { - "THUMBNAILS_PARITY_IMAGOR_URL": "http://imagor:8000", - "THUMBNAILS_PARITY_IMAGOR_MAGICK_URL": "http://imagor-magick:8000", - }, - "commands": [ - "go test -tags enable_vips ./services/thumbnails/pkg/parity/...", - ], - }, { "name": "codacy-coverage", "image": CODACY_COVERAGE_REPORTER, @@ -2647,7 +2633,7 @@ def build(): "name": "build", "image": OC_CI_GOLANG, "commands": [ - "for i in $(seq 3); do make -C opencloud build ENABLE_VIPS=1 && break || sleep 1; done", + "for i in $(seq 3); do make -C opencloud build && break || sleep 1; done", ], "environment": CI_HTTP_PROXY_ENV, }, diff --git a/Dockerfile b/Dockerfile index d5756b2717..e76bdd0a5c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,11 +26,11 @@ FROM quay.io/opencloudeu/golang-ci:1.26 AS build COPY --from=generate /opencloud /opencloud WORKDIR /opencloud/opencloud -RUN make go-generate build ENABLE_VIPS=true +RUN make go-generate build FROM alpine:3.24 -RUN apk add --no-cache attr ca-certificates curl mailcap tree vips && \ +RUN apk add --no-cache attr ca-certificates curl mailcap tree && \ echo 'hosts: files dns' >| /etc/nsswitch.conf LABEL maintainer="OpenCloud GmbH " \ diff --git a/go.mod b/go.mod index 90d16363fb..f5a2f14ca7 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,6 @@ require ( github.com/cenkalti/backoff v2.2.1+incompatible github.com/coreos/go-oidc/v3 v3.21.0 github.com/cs3org/go-cs3apis v0.0.0-20260424072047-8d9ef7076ae9 - github.com/davidbyttow/govips/v2 v2.20.0 github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e github.com/gabriel-vasile/mimetype v1.4.15 diff --git a/go.sum b/go.sum index c66e3cb7fe..94bdf1d7dc 100644 --- a/go.sum +++ b/go.sum @@ -223,8 +223,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davidbyttow/govips/v2 v2.20.0 h1:sftLOcLeI+sMPVrBiw/ulWHuMm0kKyTQ2hfnoIYSxwc= -github.com/davidbyttow/govips/v2 v2.20.0/go.mod h1:QK5liLrx7YaHC7xPcYnm4KaQIYvu9xSGrBt9goXrfgo= github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo= diff --git a/opencloud/Makefile b/opencloud/Makefile index fe9d51a7ed..fe1afc9abd 100644 --- a/opencloud/Makefile +++ b/opencloud/Makefile @@ -3,9 +3,6 @@ NAME := opencloud TAGS := disable_crypt GOARCH := $(shell go env GOARCH) CONFIG_DOCS_BASE_PATH := ../docs -ifdef ENABLE_VIPS - TAGS := ${TAGS},enable_vips -endif ifneq (, $(shell command -v go 2> /dev/null)) # suppress `command not found warnings` for non go targets in CI include ../.bingo/Variables.mk diff --git a/opencloud/docker/Dockerfile.linux.debug.amd64 b/opencloud/docker/Dockerfile.linux.debug.amd64 index 5740fa9b2c..edf3f156ca 100644 --- a/opencloud/docker/Dockerfile.linux.debug.amd64 +++ b/opencloud/docker/Dockerfile.linux.debug.amd64 @@ -3,7 +3,7 @@ FROM amd64/alpine:edge ARG VERSION="" ARG REVISION="" -RUN apk add --no-cache attr bash ca-certificates curl delve inotify-tools libc6-compat mailcap tree vips patch && \ +RUN apk add --no-cache attr bash ca-certificates curl delve inotify-tools libc6-compat mailcap tree patch && \ echo 'hosts: files dns' >| /etc/nsswitch.conf LABEL maintainer="OpenCloud GmbH " \ diff --git a/opencloud/docker/Dockerfile.linux.debug.arm64 b/opencloud/docker/Dockerfile.linux.debug.arm64 index ef80f6a32e..6341048f93 100644 --- a/opencloud/docker/Dockerfile.linux.debug.arm64 +++ b/opencloud/docker/Dockerfile.linux.debug.arm64 @@ -3,7 +3,7 @@ FROM arm64v8/alpine:edge ARG VERSION="" ARG REVISION="" -RUN apk add --no-cache attr bash ca-certificates curl delve inotify-tools libc6-compat mailcap tree vips patch && \ +RUN apk add --no-cache attr bash ca-certificates curl delve inotify-tools libc6-compat mailcap tree patch && \ echo 'hosts: files dns' >| /etc/nsswitch.conf LABEL maintainer="OpenCloud GmbH " \ diff --git a/opencloud/docker/Dockerfile.multiarch b/opencloud/docker/Dockerfile.multiarch index e6d96ced54..6fbf8a684c 100644 --- a/opencloud/docker/Dockerfile.multiarch +++ b/opencloud/docker/Dockerfile.multiarch @@ -12,7 +12,7 @@ RUN --mount=type=bind,target=/build,rw \ --mount=type=cache,target=/root/.cache \ GOOS="${TARGETOS:-linux}" GOARCH="${TARGETARCH:-amd64}" ; \ make -C ${SRCDIR:-.}/opencloud release-linux-docker-${TARGETARCH} \ - ENABLE_VIPS=true DIST=/dist \ + DIST=/dist \ VERSION="${VERSION}" EDITION="${EDITION}" \ ${STRING:+STRING="${STRING}"} @@ -23,8 +23,7 @@ ARG TARGETOS ARG TARGETARCH RUN apk add --no-cache attr bash ca-certificates curl imagemagick \ - inotify-tools libc6-compat mailcap tree vips \ - vips-magick patch && \ + inotify-tools libc6-compat mailcap tree patch && \ echo 'hosts: files dns' >| /etc/nsswitch.conf LABEL maintainer="openCloud GmbH " \ diff --git a/services/thumbnails/README.md b/services/thumbnails/README.md index f0e12e0690..ee0f495705 100644 --- a/services/thumbnails/README.md +++ b/services/thumbnails/README.md @@ -22,7 +22,7 @@ source file to this endpoint and receives the processed image back. | `POST /unsafe/fit-in/{width}x{height}/filters:{filters}` | Scale to fit within width x height, preserving aspect ratio and never upscaling | | `POST /unsafe/stretch/{width}x{height}/filters:{filters}` | Resize to the exact width x height without preserving aspect ratio (distorts) | -A `smart` segment behind the box, `POST /unsafe/{width}x{height}/smart/filters:{filters}`, asks for the crop that keeps the region carrying the image rather than the middle, which is what webdav sends for every cropping resize. With libvips that is an attention crop; the pure Go build has nothing of the kind and crops the centre, as the thumbnails service has always done without libvips. +A `smart` segment behind the box, `POST /unsafe/{width}x{height}/smart/filters:{filters}`, asks for the crop that keeps the region carrying the image rather than the middle, which is what webdav sends for every cropping resize. A real imagor answers it with an attention crop; this service has nothing of the kind and crops the centre. The path is imagor's. The filters segment is optional and may be empty (`filters:`), and an image key behind it is accepted and ignored, because the @@ -34,11 +34,10 @@ resized, while this service treats it as the box. Inside the filters segment, filter is ignored. `format` itself is optional: without it the input's own format is preserved, the same way imagor does it. An input this service cannot write (tiff, bmp) becomes a JPEG; imagor writes tiff back in its own format and only -falls back to JPEG for the ones it cannot write either. Which formats those are -depends on the build: with libvips a webp source stays a webp, the pure Go build -answers it as a JPEG because it has no webp encoder. +falls back to JPEG for the ones it cannot write either. A webp source is +answered as a JPEG, because this service has no webp encoder. -What a build can read is its own backend's answer rather than a list: the library +What this service can read is its decoders' answer rather than a list: the library that will decode the image reads the header first, so a source it cannot read answers `406` before anything is decoded, and the maximum dimensions are checked on that same header. @@ -61,13 +60,11 @@ decides it, are the webdav service's business and documented in The request body is a `multipart/form-data` upload with a single file field named `image`, typed `image/*`; an untyped part is refused the way imagor's -upload loader refuses it. Output formats are `jpg`, `png`, `gif` and, with -libvips, `webp`; the pure Go build answers `406` for `format(webp)` because it -has no webp encoder. An animated gif asked for a still format is flattened to +upload loader refuses it. Output formats are `jpg`, `png` and `gif`; `format(webp)` +is answered with `406` because this service has no webp encoder. An animated gif asked for a still format is flattened to its first frame, and a still source asked for `format(gif)` is palettised. -Reading an ICO needs libvips with its magick loader; the pure Go build answers -`406` for one. +An ICO is answered with `406`; imagor reads one only with its magick loader. An animation is the one source whose frames are all decoded here, so what its blocks declare is read before any of them is: a gif with more frames than @@ -82,7 +79,7 @@ none. The answers are imagor's: `400` for a malformed request, which includes a `format` nobody writes (anything but `jpg`, `png`, `gif` and `webp`); `406` for a source it cannot read, for an upload part that is not typed `image/*`, and for a -format this build has no encoder for (`webp` without libvips); `422` for an image +format this service has no encoder for (`webp`); `422` for an image above the configured maximum dimensions and for an animation above the frame limit; `429` when the concurrency limit is reached; `413` for a body above `THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE`. @@ -107,41 +104,12 @@ The source and the thumbnail have ceilings of their own, for different reasons. A real imagor has one pair of knobs for both, `-vips-max-width` and `-vips-max-height`, which bound every image in its pipeline, the loaded source as well as the result. Set them to the source ceiling. They are also more forgiving than this service for formats libvips can shrink while loading: a 9000 pixel wide JPEG passes a 2048 limit there, where this service refuses it on the header. -## Using libvips for Image Processing +## Supported Formats -To improve performance and to support a wider range of image formats, the -thumbnails service is able to utilize the -[libvips library](https://www.libvips.org/) for image processing. Support for -libvips needs to be enabled at buildtime and has a couple of implications: - -- With libvips support enabled, it is not possible to create a statically - linked OpenCloud binary. -- Therefore, the libvips shared libraries need to be available at runtime in - the same release that was used to build the OpenCloud binary. -- When using the OpenCloud docker images, the libvips shared libraries are - included in the image and are correctly embedded. - -Support of libvips is disabled by default. To enable it, make sure libvips -and its buildtime dependencies are installed in your build environment. For -macOS users, add the build time dependencies via: - -```shell -brew install vips pkg-config -export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" -``` - -Then you just need to set the `ENABLE_VIPS` variable on the `make` command: - -```shell -make -C opencloud build ENABLE_VIPS=1 -``` - -Or include the `enable_vips` build tag in the `go build` command: - -```shell -go build -tags enable_vips -o opencloud -o bin/opencloud ./cmd/opencloud -``` - -When building a docker image using the Dockerfile in the top-level directory of -OpenCloud, libvips support is enabled and the libvips shared libraries are -included in the resulting docker image. +This service deliberately supports a small set of formats, decoded and encoded in +pure Go: it reads `jpeg`, `png`, `gif`, `bmp`, `tiff` and `webp` and writes `jpg`, +`png` and `gif`. It is meant as a fallback generator that keeps working when +libvips or imagor need to be taken out of a deployment, for example while a +security issue in them is being fixed. A deployment that wants more formats, +webp output or an attention crop runs a real [imagor](https://imagor.net) and +points `WEBDAV_THUMBNAILS_GENERATOR_URL` at it. diff --git a/services/thumbnails/pkg/parity/build_imaging_test.go b/services/thumbnails/pkg/parity/build_imaging_test.go index c84331d19e..27a6250ebf 100644 --- a/services/thumbnails/pkg/parity/build_imaging_test.go +++ b/services/thumbnails/pkg/parity/build_imaging_test.go @@ -1,5 +1,3 @@ -//go:build !enable_vips - package parity const builtinBuild = "imaging" diff --git a/services/thumbnails/pkg/parity/build_vips_test.go b/services/thumbnails/pkg/parity/build_vips_test.go deleted file mode 100644 index 20b216f2ba..0000000000 --- a/services/thumbnails/pkg/parity/build_vips_test.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build enable_vips - -package parity - -// builtinBuild is the resize implementation compiled into this run, and the -// override key for a divergence only it has. The container images ship vips. -const builtinBuild = "vips" diff --git a/services/thumbnails/pkg/service/http/v0/push.go b/services/thumbnails/pkg/service/http/v0/push.go index 47e64d283a..8700966132 100644 --- a/services/thumbnails/pkg/service/http/v0/push.go +++ b/services/thumbnails/pkg/service/http/v0/push.go @@ -141,10 +141,9 @@ func (s Thumbnails) pushHandler(w http.ResponseWriter, r *http.Request) { MaxOutWidth: s.maxOutWidth, MaxOutHeight: s.maxOutHeight, } - // An animated gif is the one source both builds treat the same way: neither - // libvips nor the pure Go path has anything better for a paletted animation, - // so it never reaches a backend. Asking for a still format flattens it, and - // that is a backend's job again. + // An animated gif never reaches the still image backend, it is resized + // frame by frame. Asking for a still format flattens it, and that is the + // backend's job again. if bytes.HasPrefix(imgData, gifMagic) && (ext == "gif" || !hasFormat) { s.serveAnimation(w, imgData, req) diff --git a/services/thumbnails/pkg/service/http/v0/push_imaging.go b/services/thumbnails/pkg/service/http/v0/push_imaging.go index ef8a0813ed..583bca8538 100644 --- a/services/thumbnails/pkg/service/http/v0/push_imaging.go +++ b/services/thumbnails/pkg/service/http/v0/push_imaging.go @@ -1,5 +1,3 @@ -//go:build !enable_vips - package svc import ( @@ -15,9 +13,7 @@ import ( "github.com/kovidgoyal/imaging/prism/meta/autometa" ) -// The backend this build resizes with. The implementations keep their own names -// so a symbol search finds both builds' versions side by side, the variables are -// what the shared handler calls. +// The backend the service resizes with, as variables the shared handler calls. var ( loadSource = loadSourceImaging extForSourceFormat = extForSourceFormatImaging @@ -28,7 +24,7 @@ var ( encodeWebP = encodeWebPImaging ) -// imagingSource is a request's body as this build holds it between the header +// imagingSource is a request's body as the service holds it between the header // read and the resize: the bytes plus what the header said about them. The // pixels are decoded in resizeSourceImaging, so the dimension guard has its say // before anything allocates a frame buffer. @@ -38,8 +34,8 @@ type imagingSource struct { format string } -// loadSourceImaging reads the header through the stdlib decoder registry, which this -// build also decodes with: png, jpeg and gif from the stdlib, bmp, tiff and webp +// loadSourceImaging reads the header through the stdlib decoder registry, which the +// service also decodes with: png, jpeg and gif from the stdlib, bmp, tiff and webp // from the imaging library. func loadSourceImaging(data []byte) (*imagingSource, error) { config, format, err := image.DecodeConfig(bytes.NewReader(data)) @@ -51,14 +47,14 @@ func loadSourceImaging(data []byte) (*imagingSource, error) { } // Width and Height are what the header declared, so the dimension guard can ask -// before the pixels exist. Close is there because the libvips build's image has -// one; this build holds nothing that needs releasing. +// before the pixels exist. Close is a no-op, the source holds nothing that +// needs releasing. func (s *imagingSource) Width() int { return s.config.Width } func (s *imagingSource) Height() int { return s.config.Height } func (s *imagingSource) Close() {} // extForSourceFormatImaging is the output format for a request that asked for none: the -// input's own where this build can write it, a JPEG for the rest, which is how +// input's own where the service can write it, a JPEG for the rest, which is how // imagor answers a format it cannot write either. func extForSourceFormatImaging(src *imagingSource) string { switch src.format { @@ -160,8 +156,8 @@ func resizeSourceImaging(src *imagingSource, req resizeRequest) (image.Image, er return img, nil } - // smart() asks for the most interesting window, which needs libvips; - // this build crops the centre for it, the way main always did + // smart() asks for the most interesting window, which real imagor + // finds with libvips; this service crops the centre for it. return imaging.Thumbnail(img, req.Width, req.Height, imaging.Lanczos), nil } @@ -176,6 +172,6 @@ func encodeGIFImaging(w io.Writer, img image.Image) error { return gif.Encode(w, palettedAtOrigin(img, palette.Plan9), nil) } -// encodeWebPImaging refuses: there is no webp encoder in the pure Go build, so a -// deployment that needs webp output runs the libvips build or a real imagor. +// encodeWebPImaging refuses: there is no webp encoder in pure Go, so a +// deployment that needs webp output runs a real imagor. func encodeWebPImaging(io.Writer, image.Image) error { return errFormatUnsupported } diff --git a/services/thumbnails/pkg/service/http/v0/push_test.go b/services/thumbnails/pkg/service/http/v0/push_test.go index 94802b9ac1..9f3ec9ede3 100644 --- a/services/thumbnails/pkg/service/http/v0/push_test.go +++ b/services/thumbnails/pkg/service/http/v0/push_test.go @@ -226,7 +226,7 @@ var _ = Describe("outputFormatFromFilters", func() { Entry("jpeg maps onto our jpg", "format(jpeg)", "jpg", true, false), Entry("png", "format(png)", "png", true, false), Entry("gif", "format(gif)", "gif", true, false), - Entry("webp, which only the libvips build writes", "format(webp)", "webp", true, false), + Entry("webp, which only imagor writes", "format(webp)", "webp", true, false), Entry("behind another filter", "no_upscale():format(png)", "png", true, false), Entry("no format filter at all", "no_upscale()", "", false, false), Entry("an empty segment", "", "", false, false), diff --git a/services/thumbnails/pkg/service/http/v0/push_vips.go b/services/thumbnails/pkg/service/http/v0/push_vips.go deleted file mode 100644 index dd5c58a449..0000000000 --- a/services/thumbnails/pkg/service/http/v0/push_vips.go +++ /dev/null @@ -1,148 +0,0 @@ -//go:build enable_vips - -package svc - -import ( - "image/color/palette" - "image/gif" - "io" - - "github.com/davidbyttow/govips/v2/vips" -) - -// The backend this build resizes with, as variables the shared handler calls, so -// a symbol search finds both builds' implementations side by side. libvips is -// demand-driven: loading a buffer parses the header and leaves the pixels alone -// until something pulls them, so the dimension guard runs before any frame buffer -// exists. -var ( - loadSource = loadSourceVips - extForSourceFormat = extForSourceFormatVips - resizeSource = resizeSourceVips - encodeJPEG = encodeJPEGVips - encodePNG = encodePNGVips - encodeGIF = encodeGIFVips - encodeWebP = encodeWebPVips -) - -// loadSourceVips reads the header through libvips, which this build also decodes -// with, so whatever the deployed libvips reads is what this service accepts. -func loadSourceVips(data []byte) (*vips.ImageRef, error) { return vips.NewImageFromBuffer(data) } - -// extForSourceFormatVips is the output format for a request that asked for none: the -// input's own where this build can write it, a JPEG for the rest, which is how -// imagor answers a format it cannot write either. -func extForSourceFormatVips(src *vips.ImageRef) string { - switch src.Format() { - case vips.ImageTypePNG: - return "png" - case vips.ImageTypeGIF: - return "gif" - case vips.ImageTypeWEBP: - return "webp" - default: // jpeg, tiff, bmp, heif, ... - return "jpg" - } -} - -// resizeSourceVips resizes with libvips. The operation selects the resize/crop mode: -// fill (center-crop to the box, upscaling by default like real imagor's default -// resize), fit-in (fit within the box without cropping and without ever enlarging -// the source, like imagor without its upscale() filter), or stretch (resize to -// the exact box). noUpscale caps the default fill at the source size, mirroring -// imagor's no_upscale() filter. -func resizeSourceVips(src *vips.ImageRef, req resizeRequest) (*vips.ImageRef, error) { - if req.Width == 0 || req.Height == 0 { - boxW, boxH, resize, err := req.freeAxis(src.Width(), src.Height()) - if err != nil { - return nil, err - } - if resize { - if err := scaleTo(src, boxW, boxH); err != nil { - return nil, err - } - } - - return src, src.RemoveMetadata() - } - - switch req.Operation { - case OpStretch: - if err := scaleTo(src, req.Width, req.Height); err != nil { - return nil, err - } - case OpFitIn: - // imagor's fit-in only enlarges with the upscale() filter, which webdav - // never sends, so it always caps at the source size. - if err := src.ThumbnailWithSize(req.Width, req.Height, vips.InterestingNone, vips.SizeDown); err != nil { - return nil, err - } - default: // OpFill - // SizeBoth upscales a small source the way imagor's default resize does, - // no_upscale() caps it at the source size via SizeDown. - size := vips.SizeBoth - if req.NoUpscale { - size = vips.SizeDown - } - crop := vips.InterestingCentre - if req.Smart { - crop = vips.InterestingAttention - } - if err := src.ThumbnailWithSize(req.Width, req.Height, crop, size); err != nil { - return nil, err - } - } - - return src, src.RemoveMetadata() -} - -// scaleTo resizes to the exact box without preserving the aspect ratio. -func scaleTo(src *vips.ImageRef, width, height int) error { - hScale := float64(width) / float64(src.Width()) - vScale := float64(height) / float64(src.Height()) - - return src.ResizeWithVScale(hScale, vScale, vips.KernelLanczos3) -} - -// The encoders keep the image in libvips form up to here, so a JPEG comes out of -// libvips (progressive, quality 80) instead of a stdlib re-encode. -func encodeJPEGVips(w io.Writer, img *vips.ImageRef) error { - buf, _, err := img.ExportJpeg(vips.NewJpegExportParams()) - if err != nil { - return err - } - _, err = w.Write(buf) - - return err -} - -func encodePNGVips(w io.Writer, img *vips.ImageRef) error { - buf, _, err := img.ExportPng(vips.NewPngExportParams()) - if err != nil { - return err - } - _, err = w.Write(buf) - - return err -} - -// encodeGIFVips goes through the same palette the animated path uses, as libvips has -// no gif export. -func encodeGIFVips(w io.Writer, img *vips.ImageRef) error { - still, err := img.ToImage(vips.NewDefaultPNGExportParams()) - if err != nil { - return err - } - - return gif.Encode(w, palettedAtOrigin(still, palette.Plan9), nil) -} - -func encodeWebPVips(w io.Writer, img *vips.ImageRef) error { - buf, _, err := img.ExportWebp(vips.NewWebpExportParams()) - if err != nil { - return err - } - _, err = w.Write(buf) - - return err -} diff --git a/services/thumbnails/pkg/service/http/v0/resizegif.go b/services/thumbnails/pkg/service/http/v0/resizegif.go index f7c584e664..1d8443fcb3 100644 --- a/services/thumbnails/pkg/service/http/v0/resizegif.go +++ b/services/thumbnails/pkg/service/http/v0/resizegif.go @@ -10,9 +10,7 @@ import ( // resizeGIF resizes every frame of an animated gif, compositing each frame onto // a running canvas to honour the gif disposal method and re-palletting with -// Floyd-Steinberg dithering. Both backends share it: the frames go through -// imaging either way, because neither libvips nor the pure Go path has anything -// better for a paletted animation. Code adapted from +// Floyd-Steinberg dithering. Code adapted from // https://github.com/willnorris/gifresize. The only error is errBoxTooLarge. func resizeGIF(m *gif.GIF, req resizeRequest) (*gif.GIF, error) { srcX, srcY := m.Config.Width, m.Config.Height diff --git a/services/webdav/README.md b/services/webdav/README.md index 5b5aa464d7..a3d089ea7f 100644 --- a/services/webdav/README.md +++ b/services/webdav/README.md @@ -64,7 +64,7 @@ Without a processor two things decide, in this order. An unconstrained axis is a #### Thumbnail Generator -The thumbnails themselves are made by a generator the webdav service POSTs to, configured with `WEBDAV_THUMBNAILS_GENERATOR_URL` (and `WEBDAV_THUMBNAILS_GENERATOR_TIMEOUT`). The built-in thumbnails service speaks the imagor image endpoint, so a real [imagor](https://imagor.net) can be put in its place without changing anything else. A source the generator cannot read answers `404`, one that is too large `403`, and `WEBDAV_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` caps what is sent at all; `OC_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` sets this and the generator's own cap together, so one does not send what the other refuses. A generator that refuses because it is busy answers `429` with its own `Retry-After`, so a client can come back instead of treating it as a missing preview. The same cap bounds an image webdav extracts itself, the cover of an audio file or the thumbnail inside a geogebra container, because a compressed entry says nothing about its size until it is read. A cropping resize asks the generator for a smart crop, so what survives is the region that carries the image; a generator without libvips answers the same request with a centre crop. +The thumbnails themselves are made by a generator the webdav service POSTs to, configured with `WEBDAV_THUMBNAILS_GENERATOR_URL` (and `WEBDAV_THUMBNAILS_GENERATOR_TIMEOUT`). The built-in thumbnails service speaks the imagor image endpoint, so a real [imagor](https://imagor.net) can be put in its place without changing anything else. A source the generator cannot read answers `404`, one that is too large `403`, and `WEBDAV_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` caps what is sent at all; `OC_THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE` sets this and the generator's own cap together, so one does not send what the other refuses. A generator that refuses because it is busy answers `429` with its own `Retry-After`, so a client can come back instead of treating it as a missing preview. The same cap bounds an image webdav extracts itself, the cover of an audio file or the thumbnail inside a geogebra container, because a compressed entry says nothing about its size until it is read. A cropping resize asks the generator for a smart crop, so what survives is the region that carries the image; the built-in thumbnails service answers the same request with a centre crop. Three settings say what is made of what. Each one is merged onto the built-in defaults, which is what their `ADDITIONAL` says: naming one type does not take the answer away from the others, and an entry for a type the defaults already answer for replaces that one entry. The first takes bare mime types, the other two take `key:value` entries: diff --git a/services/webdav/pkg/generator/url.go b/services/webdav/pkg/generator/url.go index 6b80745148..f215cad7d0 100644 --- a/services/webdav/pkg/generator/url.go +++ b/services/webdav/pkg/generator/url.go @@ -42,8 +42,8 @@ func operationSegment(op string) string { // // A cropping resize also asks for the smart crop, so the generator keeps the // region that carries the image instead of whatever sits in the middle. What a -// generator makes of it is its own: real imagor and the libvips build crop on -// attention, the pure Go build has no such thing and crops the centre. +// generator makes of it is its own: real imagor crops on attention, the +// built-in thumbnails service has no such thing and crops the centre. func BuildURL(baseURL string, width, height int32, operation, format string, noUpscale bool) string { base := strings.TrimRight(baseURL, "/") diff --git a/tests/acceptance/features/coreApiWebdavPreviews/previews.feature b/tests/acceptance/features/coreApiWebdavPreviews/previews.feature index 277e657600..d545bd020d 100644 --- a/tests/acceptance/features/coreApiWebdavPreviews/previews.feature +++ b/tests/acceptance/features/coreApiWebdavPreviews/previews.feature @@ -236,7 +236,7 @@ Feature: previews of files downloaded through the webdav API | new | | spaces | - @need-build-with-VIPS @issue-1451 + @issue-1451 Scenario Outline: it should update the preview content if the file content is updated (content with UTF chars) Given using DAV path And user "Alice" has uploaded file "filesForUpload/lorem.txt" to "/lorem.txt" @@ -250,7 +250,7 @@ Feature: previews of files downloaded through the webdav API | new | | spaces | - @need-build-with-VIPS @issue-1452 + @issue-1452 Scenario Outline: download preview of the text file Given using DAV path And user "Alice" has uploaded file "filesForUpload/lorem.txt" to "/lorem.txt" @@ -359,7 +359,7 @@ Feature: previews of files downloaded through the webdav API | new | | spaces | - @need-build-with-VIPS + Scenario Outline: download previews of an image with different processors Given using DAV path And user "Alice" has uploaded file "filesForUpload/testavatar.jpg" to "/testimage.jpg" diff --git a/tests/acceptance/fixtures/fill.jpg b/tests/acceptance/fixtures/fill.jpg index b240453454024046d745d8b593d6b4ab7d1aaa4d..a2eccea067d678d26345246959288bd3896a548c 100644 GIT binary patch literal 836 zcmex=KU|?co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Y7fs(LKH9^K(sp_)X;hn*ArJ{y@cnm*-7hY>A#d+vEAxBTsjh#7{ZKd1#V9 zyM?_^aqKjU%IF*C7H!@CP=2?dfScaG58IBP-TeFZ=Dt12YlC)en0HP?uH;4jJFd*Sal>CQM&CYdTe>9U4Ks&xh1WON+>cth;+6kOlbjFEVh0>PHA=p` UuJVO}YpJVv!joH@?f>5d02M|o761SM literal 944 zcmb7BT}TvB82#>@pB+c5nVn@;*JNk>-IXv+;r` ziDE{E=-9j^OL980vz-oAb>$VgUAYBYRaNt81;r)aQg4pC%wOj57kRuM(}dV;Hc=22 zQB*uG)#dr`G9G~}fCd^v@`1{Pk%{pHaxgMJYl~qi$K#QckPRn57}j_PSquRxF%r&y zPD~_yhhFw~&=bON5JhK9P$PVXcmQ<6gLud36nDHnzkqq*{+AR{7_5zzSeXQ zK1iqbXI`H8JpLj#G1J_2U+)~haceZuqh6Vh_Rm-JjUU{LZkp-Fn)kn41Y}(cgj&K2 zk+ajwT?O@cPyfS_>TQo(E9y(SPHk5zYXxCRd-|jMSmDUT&OLu($)<4as1pU&1g+sp z-+m3?Kb&UY>$)NkkS%MoaY?!OT)*mzB$4{>h%k=DH2asHWp}^;gC;CK49-g&g3l? mR($y$`Pn!yT`ns3X6K^21=@FXs%my97PAk3XoRQ%#@oLXgTFZd diff --git a/tests/acceptance/fixtures/text-file-fixture.jpg b/tests/acceptance/fixtures/text-file-fixture.jpg index 59b64a93d64ce09750910e20a8e11c601b74ed7e..0d632986e78d64a5a043862de3adaf5d23e1a0f1 100644 GIT binary patch literal 63375 zcmd?QcT`hfw=Nut6lo$&I?@#ZfzYcWU8G41ReFFB>7gSE(h;eK4$=t-gx;h#=@20F zB2^%f76IY%d(XLdeE*&E-9PSqzwxax=E%s{dnEJOYwoq?^Q<{<=57`M9{?moM8rgQ zNQjAvNl8iWlG9R0pfSQC5KnNhf;{@PS;}KBf-Spt)0|0n; z@cuOb|2gpR2?*~H5tESKCA$Z}$0H!XCnUIYhmi30&Y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uO(TCt(B?EA7g(pBrKaqhcBI9`*>i$g%is1d{^w}c#a>4F zL-TG&%n5~GY;>eM5giHmKE<#l+NJ4g^UR$-*R!S12J}RY45aXl~EOC7_7im*o40j1>XF3(GDk zj}qmTv@c7D?T00~t|Gan-UCveE6fH*%nA@8av66mh~ViofJalrnh4-av7nOcS#x&q z-9(2ONNS6b%eixfKGdIhWaL<-TTum#tzxv!1w(2uCFHfO?W$w8@hhrmiEUT4@SWI! z!jc?w_iW|eLs~NC%_&{Q>g+OH#XMURZ;~l3@i`1C;0hPuOU0U0v9Kp3YCI#@#_fH~ z{SdHAE2iF7QV`ky(^k(-OB_LX|=`(;6OT~y5hRA^R;A9EzJ*qIdc_0 z8SR-`IdwM0{h?LC;L(*%<|x2&A2RW$2Vr-2IYTnLDiXLw3r5>vI>Qv+{>k`UC{z5z zMbriKE4VV8i85KKYUN)v89XZ%>z1wI1A~~|aBnF5@ZSM6Z+&!A5KBf2Wwu~; zA=N5oZl_c*^V~Pa28HJl0JE6nvJnMJU1lR2qSFVRN+?jWE1O|%0})ZgdG8i-iPr{> zQxKjx4FP>cDOr3R>Hx9eB5kR=7y`RRGd=~~XC$f)!6a&53Iy5>&hMo#>>Y+QKtM K_J933pa0pXVj@@o diff --git a/tests/acceptance/fixtures/thumbnail.jpg b/tests/acceptance/fixtures/thumbnail.jpg index b240453454024046d745d8b593d6b4ab7d1aaa4d..a2eccea067d678d26345246959288bd3896a548c 100644 GIT binary patch literal 836 zcmex=KU|?coW@chxW@Tkz0jjJ8$}zAA zvI;30I#U-U>$dGXcJ4ZK_{h;?$4{I*b?NeztJkjIxOwa0qsLF4K70P+<*SdM zK7aZ8?fZ|PzZe;qA>IL!5Dy{wM-b>ACKeWE7Iu(-7@5j}m|2j8Rnd@5$T5&Tu~1ma zsF6d&Y2w0-2RW6EgFc8R6KQ!#m{`Vr(Mu#brIP!m}`f_n(=pZ~WQc$gW15ymXY zV9)TmOFMOs-Q~sq8PZ~xEmSGe338XoX%U_ydiQ&yLeF1|XAA!`wA6jk6 zRIM?(>$GWRazs4CB4YuG4|moXAAjsRqsV)s>hew&@oS&Dxw9)=PsPOOZklr{WRl%S z1)fO-2FAYaN5#cXC^lWXryaXQLRoLYq}$zjyt^&sb{rRNb(J|&cgbz#N7jeAH+n4E zBAh=(aLQL&s;{u+|GfO~kX3=9lx3_^^|42(b)2um@tg6S|ITN=ua1F|)sYM6j* zVJ3w7%yt&AdZ2+2P|nEkf*Ht!(rgS26WAG8fC2_ah6aoiA#6sV2@DIM;)VtWj0+$p z{{PRwz_b8jq5@D4GZGufW%z%a!I^=Lg_Vt!g^i7sjh&s1gG+#mi<6T}gpZ#`KwLyZ zLR>^lOiET&UP@Y7ModgWM?qOlT~kX_QeM|USHnP6LsJ7}2qQZ?I~NC+Fc+7whLo6; z2Fc+6AqGJX1_cHMW=16jCP7AKLB{__7^HxK$O;NZ1OR#!=w6_l7$XoM#6c`(mjAaH zc$gU(m;{&wfLfpMO01tXvncW84Dq@1f`{L$H>a` zF*<8o?6tGY`)pa(74aMrO}TusZcjbPMnMKpOdtbBA+SDXMn-$aY2KPs&I6T+3ZlD< zK@hBp38boH6;O$y00R>vGczl~C`Klr;X=X+j)s9ji4&oYVY6qtQ4$lYaF8J+@%>sq zwl3}iyUujH^(wjQ<~Um}OH@R?W7eaD{$&{(w&z&ROgwiVXtW&AXeK70gWzT}3Mv{h zI4UF-1}=no(q8d_Pmp1Q{_-RvyMroWYgeBQvG%)K-I*+AA~31%Woq6xqvXp!8y;sf zMd$9(t@qbw3KTwUV z04PS0-41j*gQ0?BU?VIz1wk?ZXKPQdT}?7SfOZ G-vj_!Y{*{# diff --git a/tests/acceptance/fixtures/unicode-fixture.jpg b/tests/acceptance/fixtures/unicode-fixture.jpg index edbc6770c76cf20ed9f00b8572734799aa8bf56b..d7d687046499486ac92f73d57c50e997f550489b 100644 GIT binary patch literal 18995 zcmeIzc|2789tZFuGIL(@{qvw-{>c?9fM{P%2u+ zyNwLY^md{QAP59POjJy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UVqA6h|jh2E&m3iGaCVYm(BWijj zyNARzA7GC(1>a4~?~*m?9Z2S^*jLnq7Z_OdlIOT)?*nO3Puz@FGC3qV5t>}ykOI$< z89rYZk~i?8_SouqQJ| zUl}?1vcz%~dM&6PB06I9<`iG3o}%kK`$=HZ>yWn4S#f!*@rQ(SIwnOgVM23^W-GV2 z4w^md;f?j1P`hn)$65JB(q+x^)~QY9Lw8l%MS#iZHEl<2brlH}=?_OT`oM#XVyV-9 zS+Ek~ryI)?ljx?8dX1v1wW!J?cBJ+m=H}UiDW@r1UL$2y)z`)AWwW_mw=7diQ`f6E zUA0)5fC@7<7+goEA8{%1h+R4#Wy@$@bgZ~gF;9ZtfIW@*Pjaz{HY3#5;Q@buw3S+g zy|i9IL#qLk;FWRf7{!OY7EV)$ZoZ%id6Km)(F$Vd29%hr27M*-nASL4ISDfoZFO0f zwLGC-VW~>|T9W@ya5Burg>Q75ztZCIR>nwWmz=xwPG5(MzsR%R(TRHbaQ zwZ&U%2nHBeo>{mm8t_5zwS`+-N~kGoKsiZl5@n`5wF4+3hUpIHK7H2W%%i`YY_l`? Ef5I$j-~a#s diff --git a/vendor/github.com/davidbyttow/govips/v2/LICENSE b/vendor/github.com/davidbyttow/govips/v2/LICENSE deleted file mode 100644 index 8d0891d788..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License - -Copyright (c) Simple Things LLC and contributors - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/error.go b/vendor/github.com/davidbyttow/govips/v2/vips/error.go deleted file mode 100644 index 08eb41e78f..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/error.go +++ /dev/null @@ -1,39 +0,0 @@ -package vips - -// #include -import "C" - -import ( - "errors" - "fmt" - dbg "runtime/debug" - "unsafe" -) - -var ( - // ErrUnsupportedImageFormat when image type is unsupported - ErrUnsupportedImageFormat = errors.New("unsupported image format") -) - -func handleImageError(out *C.VipsImage) error { - if out != nil { - clearImage(out) - } - - return handleVipsError() -} - -func handleSaveBufferError(out unsafe.Pointer) error { - if out != nil { - gFreePointer(out) - } - - return handleVipsError() -} - -func handleVipsError() error { - s := C.GoString(C.vips_error_buffer()) - C.vips_error_clear() - - return fmt.Errorf("%v\nStack:\n%s", s, dbg.Stack()) -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.c b/vendor/github.com/davidbyttow/govips/v2/vips/foreign.c deleted file mode 100644 index 34cbf78a42..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.c +++ /dev/null @@ -1,628 +0,0 @@ -#include "foreign.h" - -#include "lang.h" - -void set_bool_param(Param *p, gboolean b) { - p->type = PARAM_TYPE_BOOL; - p->value.b = b; - p->is_set = TRUE; -} - -void set_int_param(Param *p, gint i) { - p->type = PARAM_TYPE_INT; - p->value.i = i; - p->is_set = TRUE; -} - -void set_double_param(Param *p, gdouble d) { - p->type = PARAM_TYPE_DOUBLE; - p->value.d = d; - p->is_set = TRUE; -} - -int load_image_buffer(LoadParams *params, void *buf, size_t len, - VipsImage **out) { - int code = 1; - ImageType imageType = params->inputFormat; - - if (imageType == JPEG) { - // shrink: int, fail: bool, autorotate: bool - code = vips_jpegload_buffer(buf, len, out, "fail", params->fail, - "autorotate", params->autorotate, "shrink", - params->jpegShrink, "access", params->access, NULL); - } else if (imageType == PNG) { - code = vips_pngload_buffer(buf, len, out, "access", params->access, NULL); - } else if (imageType == WEBP) { - // page: int, n: int, scale: double - code = vips_webpload_buffer(buf, len, out, "page", params->page, "n", - params->n, "access", params->access, NULL); - } else if (imageType == TIFF) { - // page: int, n: int, autorotate: bool, subifd: int - code = - vips_tiffload_buffer(buf, len, out, "page", params->page, "n", - params->n, "autorotate", params->autorotate, "access", params->access, NULL); - } else if (imageType == GIF) { - // page: int, n: int, scale: double - code = vips_gifload_buffer(buf, len, out, "page", params->page, "n", - params->n, "access", params->access, NULL); - } else if (imageType == PDF) { - // page: int, n: int, dpi: double, scale: double, background: color - code = vips_pdfload_buffer(buf, len, out, "page", params->page, "n", - params->n, "dpi", params->dpi, "access", params->access, NULL); - } else if (imageType == SVG) { - // dpi: double, scale: double, unlimited: bool - code = vips_svgload_buffer(buf, len, out, "dpi", params->dpi, "unlimited", - params->svgUnlimited, "access", params->access, NULL); - } else if (imageType == HEIF) { - // added autorotate on load as currently it addresses orientation issues - // https://github.com/libvips/libvips/pull/1680 - // page: int, n: int, thumbnail: bool - code = vips_heifload_buffer(buf, len, out, "page", params->page, "n", - params->n, "thumbnail", params->heifThumbnail, - "autorotate", TRUE, "access", params->access, NULL); - } else if (imageType == MAGICK) { - // page: int, n: int, density: string - code = vips_magickload_buffer(buf, len, out, "page", params->page, "n", - params->n, "access", params->access, NULL); - } else if (imageType == AVIF) { - code = vips_heifload_buffer(buf, len, out, "page", params->page, "n", - params->n, "thumbnail", params->heifThumbnail, - "autorotate", params->autorotate, "access", params->access, NULL); - - } - #if (VIPS_MAJOR_VERSION >= 8) && (VIPS_MINOR_VERSION >= 11) - else if (imageType == JP2K) { - code = vips_jp2kload_buffer(buf, len, out, "page", params->page, "access", params->access, NULL); - } - #endif - - return code; -} - -#define MAYBE_SET_BOOL(OP, PARAM, NAME) \ - if (PARAM.is_set) { \ - vips_object_set(VIPS_OBJECT(OP), NAME, PARAM.value.b, NULL); \ - } - -#define MAYBE_SET_INT(OP, PARAM, NAME) \ - if (PARAM.is_set) { \ - vips_object_set(VIPS_OBJECT(OP), NAME, PARAM.value.i, NULL); \ - } - -#define MAYBE_SET_DOUBLE(OP, PARAM, NAME) \ - if (PARAM.is_set) { \ - vips_object_set(VIPS_OBJECT(OP), NAME, PARAM.value.d, NULL); \ - } - -typedef int (*SetLoadOptionsFn)(VipsOperation *operation, LoadParams *params); - -int set_jpegload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_BOOL(operation, params->autorotate, "autorotate"); - MAYBE_SET_BOOL(operation, params->fail, "fail"); - MAYBE_SET_INT(operation, params->jpegShrink, "shrink"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_pngload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_BOOL(operation, params->fail, "fail"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_webpload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_INT(operation, params->access, "access"); - MAYBE_SET_DOUBLE(operation, params->webpScale, "scale"); - return 0; -} - -int set_tiffload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_BOOL(operation, params->autorotate, "autorotate"); - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_gifload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_pdfload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_DOUBLE(operation, params->dpi, "dpi"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_svgload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_BOOL(operation, params->svgUnlimited, "unlimited"); - MAYBE_SET_DOUBLE(operation, params->dpi, "dpi"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_heifload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_BOOL(operation, params->autorotate, "autorotate"); - MAYBE_SET_BOOL(operation, params->heifThumbnail, "thumbnail"); - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_jp2kload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int set_jxlload_options(VipsOperation *operation, LoadParams *params) { - // nothing need to do - return 0; -} - -int set_magickload_options(VipsOperation *operation, LoadParams *params) { - MAYBE_SET_INT(operation, params->page, "page"); - MAYBE_SET_INT(operation, params->n, "n"); - MAYBE_SET_INT(operation, params->access, "access"); - return 0; -} - -int load_buffer(const char *operationName, void *buf, size_t len, - LoadParams *params, SetLoadOptionsFn setLoadOptions) { - VipsBlob *blob = vips_blob_new(NULL, buf, len); - - VipsOperation *operation = vips_operation_new(operationName); - if (!operation) { - return 1; - } - - if (vips_object_set(VIPS_OBJECT(operation), "buffer", blob, NULL)) { - vips_area_unref(VIPS_AREA(blob)); - return 1; - } - - vips_area_unref(VIPS_AREA(blob)); - - if (setLoadOptions(operation, params)) { - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - return 1; - } - - if (vips_cache_operation_buildp(&operation)) { - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - return 1; - } - - g_object_get(VIPS_OBJECT(operation), "out", ¶ms->outputImage, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - - return 0; -} - -typedef int (*SetSaveOptionsFn)(VipsOperation *operation, SaveParams *params); - -int save_buffer(const char *operationName, SaveParams *params, - SetSaveOptionsFn setSaveOptions) { - VipsBlob *blob; - VipsOperation *operation = vips_operation_new(operationName); - if (!operation) { - return 1; - } - - if (vips_object_set(VIPS_OBJECT(operation), "in", params->inputImage, NULL)) { - return 1; - } - - if (setSaveOptions(operation, params)) { - g_object_unref(operation); - return 1; - } - - // "keep" is set here rather than in each per-format setter so every - // saver gets it the same way. It overrides the deprecated "strip". - if (params->keepSet && - vips_object_set(VIPS_OBJECT(operation), "keep", params->keep, NULL)) { - g_object_unref(operation); - return 1; - } - - if (vips_cache_operation_buildp(&operation)) { - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - return 1; - } - - g_object_get(VIPS_OBJECT(operation), "buffer", &blob, NULL); - g_object_unref(operation); - - VipsArea *area = VIPS_AREA(blob); - - params->outputBuffer = (char *)(area->data); - params->outputLen = area->length; - area->free_fn = NULL; - vips_area_unref(area); - - return 0; -} - -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-jpegsave-buffer -int set_jpegsave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set( - VIPS_OBJECT(operation), "strip", params->stripMetadata, "optimize_coding", - params->jpegOptimizeCoding, "interlace", params->interlace, - "subsample_mode", params->jpegSubsample, "trellis_quant", - params->jpegTrellisQuant, "overshoot_deringing", - params->jpegOvershootDeringing, "optimize_scans", - params->jpegOptimizeScans, "quant_table", params->jpegQuantTable, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-pngsave-buffer -int set_pngsave_options(VipsOperation *operation, SaveParams *params) { - int ret = - vips_object_set(VIPS_OBJECT(operation), "strip", params->stripMetadata, - "compression", params->pngCompression, "interlace", - params->interlace, "filter", params->pngFilter, "palette", - params->pngPalette, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - if (!ret && params->pngDither) { - ret = vips_object_set(VIPS_OBJECT(operation), "dither", params->pngDither, NULL); - } - - if (!ret && params->pngBitdepth) { - ret = vips_object_set(VIPS_OBJECT(operation), "bitdepth", params->pngBitdepth, NULL); - } - - // TODO: Handle `profile` param. - - return ret; -} - -// https://github.com/libvips/libvips/blob/master/libvips/foreign/webpsave.c#L524 -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-webpsave-buffer -int set_webpsave_options(VipsOperation *operation, SaveParams *params) { - int ret = - vips_object_set(VIPS_OBJECT(operation), - "strip", params->stripMetadata, - "lossless", params->webpLossless, - "near_lossless", params->webpNearLossless, - "reduction_effort", params->webpReductionEffort, - "min_size", params->webpMinSize, - "kmin", params->webpKMin, - "kmax", params->webpKMax, - NULL); - - // Only pass a profile the caller chose; leaving "profile" unset lets - // strip/keep decide about the source image's own ICC, as for the other - // savers. With StripMetadata and no Keep, still pass "none": webpsave in - // libvips 8.14.0-8.14.1 ignores "strip" (a shadowed field, fixed in - // 8.14.2), and "none" is what keeps the ICC out there. Elsewhere strip - // already drops it. - if (!ret && params->webpIccProfile) { - ret = vips_object_set(VIPS_OBJECT(operation), "profile", - params->webpIccProfile, NULL); - } else if (!ret && params->stripMetadata && !params->keepSet) { - ret = vips_object_set(VIPS_OBJECT(operation), "profile", "none", NULL); - } - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - if (!ret && params->webpTargetSize) { - ret = vips_object_set(VIPS_OBJECT(operation), "target_size", params->webpTargetSize, NULL); - } - - return ret; -} - -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-tiffsave-buffer -int set_tiffsave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set( - VIPS_OBJECT(operation), "strip", params->stripMetadata, "compression", - params->tiffCompression, "predictor", params->tiffPredictor, "pyramid", - params->tiffPyramid, "tile_height", params->tiffTileHeight, "tile_width", - params->tiffTileWidth, "tile", params->tiffTile, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-magicksave-buffer -int set_magicksave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set(VIPS_OBJECT(operation), "format", params->magickFormat, - "optimize_gif_frames", params->magickOptimizeGifFrames, - "optimize_gif_transparency", params->magickOptimizeGifTransparency, - "bitdepth", params->magickBitDepth, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "quality", params->quality, - NULL); - } - return ret; -} - -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html#vips-gifsave-buffer -int set_gifsave_options(VipsOperation *operation, SaveParams *params) { - int ret = 0; - // See for argument values: https://www.libvips.org/API/current/VipsForeignSave.html#vips-gifsave - if (params->gifDither > 0.0 && params->gifDither <= 10) { - ret = vips_object_set(VIPS_OBJECT(operation), "dither", params->gifDither, NULL); - } - if (params->gifEffort >= 1 && params->gifEffort <= 10) { - ret = vips_object_set(VIPS_OBJECT(operation), "effort", params->gifEffort, NULL); - } - if (params->gifBitdepth >= 1 && params->gifBitdepth <= 8) { - ret = vips_object_set(VIPS_OBJECT(operation), "bitdepth", params->gifBitdepth, NULL); - } - return ret; -} - -// https://github.com/libvips/libvips/blob/master/libvips/foreign/heifsave.c#L653 -int set_heifsave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set(VIPS_OBJECT(operation), "lossless", - params->heifLossless, NULL); - -#if (VIPS_MAJOR_VERSION >= 8) && (VIPS_MINOR_VERSION >= 13) - if (!ret && params->heifBitdepth && params->heifEffort) { - ret = vips_object_set(VIPS_OBJECT(operation), "bitdepth", - params->heifBitdepth, "effort", params->heifEffort, - NULL); - } -#else - if (!ret && params->heifEffort) { - ret = vips_object_set(VIPS_OBJECT(operation), "speed", params->heifEffort, - NULL); - } -#endif - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -// https://github.com/libvips/libvips/blob/master/libvips/foreign/heifsave.c#L653 -int set_avifsave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set(VIPS_OBJECT(operation), "strip", params->stripMetadata, "compression", - VIPS_FOREIGN_HEIF_COMPRESSION_AV1, "lossless", - params->heifLossless, NULL); - -#if (VIPS_MAJOR_VERSION >= 8) && (VIPS_MINOR_VERSION >= 13) - if (!ret && params->heifBitdepth && params->heifEffort) { - ret = vips_object_set(VIPS_OBJECT(operation), "bitdepth", - params->heifBitdepth, "effort", params->heifEffort, - NULL); - } -#else - if (!ret && params->heifEffort) { - ret = vips_object_set(VIPS_OBJECT(operation), "speed", params->heifEffort, - NULL); - } -#endif - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -int set_jp2ksave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set( - VIPS_OBJECT(operation), "subsample_mode", params->jpegSubsample, - "tile_height", params->jp2kTileHeight, "tile_width", params->jp2kTileWidth, - "lossless", params->jp2kLossless, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -int set_jxlsave_options(VipsOperation *operation, SaveParams *params) { - int ret = vips_object_set( - VIPS_OBJECT(operation), "tier", params->jxlTier, - "distance", params->jxlDistance, "effort", params->jxlEffort, - "lossless", params->jxlLossless, NULL); - - if (!ret && params->quality) { - ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL); - } - - return ret; -} - -int load_from_buffer(LoadParams *params, void *buf, size_t len) { - switch (params->inputFormat) { - case JPEG: - return load_buffer("jpegload_buffer", buf, len, params, - set_jpegload_options); - case PNG: - return load_buffer("pngload_buffer", buf, len, params, - set_pngload_options); - case WEBP: - return load_buffer("webpload_buffer", buf, len, params, - set_webpload_options); - case HEIF: - return load_buffer("heifload_buffer", buf, len, params, - set_heifload_options); - case TIFF: - return load_buffer("tiffload_buffer", buf, len, params, - set_tiffload_options); - case SVG: - return load_buffer("svgload_buffer", buf, len, params, - set_svgload_options); - case GIF: - return load_buffer("gifload_buffer", buf, len, params, - set_gifload_options); - case PDF: - return load_buffer("pdfload_buffer", buf, len, params, - set_pdfload_options); - case MAGICK: - return load_buffer("magickload_buffer", buf, len, params, - set_magickload_options); - case AVIF: - return load_buffer("heifload_buffer", buf, len, params, - set_heifload_options); - case JP2K: - return load_buffer("jp2kload_buffer", buf, len, params, - set_jp2kload_options); - case JXL: - return load_buffer("jxlload_buffer", buf, len, params, - set_jxlload_options); - default: - g_warning("Unsupported input type given: %d", params->inputFormat); - } - return 1; -} - -int save_to_buffer(SaveParams *params) { - switch (params->outputFormat) { - case JPEG: - return save_buffer("jpegsave_buffer", params, set_jpegsave_options); - case PNG: - return save_buffer("pngsave_buffer", params, set_pngsave_options); - case WEBP: - return save_buffer("webpsave_buffer", params, set_webpsave_options); - case HEIF: - return save_buffer("heifsave_buffer", params, set_heifsave_options); - case TIFF: - return save_buffer("tiffsave_buffer", params, set_tiffsave_options); - case GIF: -#if (VIPS_MAJOR_VERSION >= 8) && (VIPS_MINOR_VERSION >= 12) - return save_buffer("gifsave_buffer", params, set_gifsave_options); -#else - // Gif save through ImageMagick below Vips Version 8.12 - params->magickFormat="GIF"; - params->magickOptimizeGifFrames=FALSE; - params->magickOptimizeGifTransparency=FALSE; - params->magickBitDepth=params->gifBitdepth; - return save_buffer("magicksave_buffer", params, set_magicksave_options); -#endif - case AVIF: - return save_buffer("heifsave_buffer", params, set_avifsave_options); - case JP2K: - return save_buffer("jp2ksave_buffer", params, set_jp2ksave_options); - case JXL: - return save_buffer("jxlsave_buffer", params, set_jxlsave_options); - case MAGICK: - return save_buffer("magicksave_buffer", params, set_magicksave_options); - default: - g_warning("Unsupported output type given: %d", params->outputFormat); - } - return 1; -} - -LoadParams create_load_params(ImageType inputFormat) { - Param defaultParam = {}; - LoadParams p = { - .inputFormat = inputFormat, - .inputBlob = NULL, - .outputImage = NULL, - .autorotate = defaultParam, - .fail = defaultParam, - .page = defaultParam, - .n = defaultParam, - .dpi = defaultParam, - .jpegShrink = defaultParam, - .webpScale = defaultParam, - .heifThumbnail = defaultParam, - .svgUnlimited = defaultParam, - .access = defaultParam, - }; - return p; -} - -// TODO: Change to same pattern as ImportParams - -static SaveParams defaultSaveParams = { - .inputImage = NULL, - .outputBuffer = NULL, - .outputFormat = JPEG, - .outputLen = 0, - - .interlace = FALSE, - .quality = 0, - .stripMetadata = FALSE, - .keep = 0, - .keepSet = FALSE, - - .jpegOptimizeCoding = FALSE, - .jpegSubsample = VIPS_FOREIGN_SUBSAMPLE_ON, - .jpegTrellisQuant = FALSE, - .jpegOvershootDeringing = FALSE, - .jpegOptimizeScans = FALSE, - .jpegQuantTable = 0, - - .pngCompression = 6, - .pngPalette = FALSE, - .pngBitdepth = 0, - .pngDither = 0, - .pngFilter = VIPS_FOREIGN_PNG_FILTER_NONE, - - .gifDither = 0.0, - .gifEffort = 0, - .gifBitdepth = 0, - - .webpLossless = FALSE, - .webpNearLossless = FALSE, - .webpReductionEffort = 4, - .webpIccProfile = NULL, - .webpKMax = 0, - .webpKMin = 0, - .webpMinSize = FALSE, - .webpTargetSize = 0, - - .heifBitdepth = 8, - .heifLossless = FALSE, - .heifEffort = 5, - - .tiffCompression = VIPS_FOREIGN_TIFF_COMPRESSION_LZW, - .tiffPredictor = VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL, - .tiffPyramid = FALSE, - .tiffTile = FALSE, - .tiffTileHeight = 256, - .tiffTileWidth = 256, - - .jp2kLossless = FALSE, - .jp2kTileHeight = 512, - .jp2kTileWidth = 512, - - .jxlTier = 0, - .jxlDistance = 1.0, - .jxlEffort = 7, - .jxlLossless = FALSE, - }; - -SaveParams create_save_params(ImageType outputFormat) { - SaveParams params = defaultSaveParams; - params.outputFormat = outputFormat; - return params; -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.go b/vendor/github.com/davidbyttow/govips/v2/vips/foreign.go deleted file mode 100644 index 3d40df2c19..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.go +++ /dev/null @@ -1,759 +0,0 @@ -package vips - -// #include "foreign.h" -import "C" -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "math" - "runtime" - "unsafe" - - "golang.org/x/net/html/charset" -) - -// SubsampleMode correlates to a libvips subsample mode -type SubsampleMode int - -// SubsampleMode enum correlating to libvips subsample modes -const ( - VipsForeignSubsampleAuto SubsampleMode = C.VIPS_FOREIGN_SUBSAMPLE_AUTO - VipsForeignSubsampleOn SubsampleMode = C.VIPS_FOREIGN_SUBSAMPLE_ON - VipsForeignSubsampleOff SubsampleMode = C.VIPS_FOREIGN_SUBSAMPLE_OFF - VipsForeignSubsampleLast SubsampleMode = C.VIPS_FOREIGN_SUBSAMPLE_LAST -) - -// ForeignKeep flags select which metadata a saver retains (libvips's "keep" -// save option, libvips 8.15+). Values may be combined with |. -// -// The values are libvips's VipsForeignKeep bits written as literals rather -// than C.VIPS_FOREIGN_KEEP_* because those macros don't exist in the -// libvips 8.14 headers govips still builds against. -const ( - // ForeignKeepNone keeps no metadata. It is a Go-only sentinel (like - // KernelAuto) translated to VIPS_FOREIGN_KEEP_NONE (0) before reaching - // libvips, because the zero value of the Keep fields means "unset". - // It is a high bit rather than -1 so that it still composes with |. - ForeignKeepNone ForeignKeep = 1 << 30 - ForeignKeepExif ForeignKeep = 1 << 0 - ForeignKeepXmp ForeignKeep = 1 << 1 - ForeignKeepIptc ForeignKeep = 1 << 2 - ForeignKeepIcc ForeignKeep = 1 << 3 - ForeignKeepOther ForeignKeep = 1 << 4 - // ForeignKeepGainmap keeps the UltraHDR gain map (libvips 8.18+). Older - // libvips cannot load gain maps, so the bit is dropped there: combined - // with other flags it changes nothing, but on its own it keeps no - // metadata at all, exactly like ForeignKeepNone. - ForeignKeepGainmap ForeignKeep = 1 << 5 - // ForeignKeepAll keeps all metadata the running libvips supports. - ForeignKeepAll = ForeignKeepExif | ForeignKeepXmp | ForeignKeepIptc | - ForeignKeepIcc | ForeignKeepOther | ForeignKeepGainmap -) - -// errKeepUnsupported is returned by resolveKeep when the libvips version -// predates the "keep" save option. -var errKeepUnsupported = errors.New("keep requires libvips 8.15+") - -// resolveKeep maps a ForeignKeep value to the libvips "keep" flags for the -// given libvips version. set is false when k is unset (zero), in which case -// the caller must not pass "keep" at all and StripMetadata decides. -func resolveKeep(k ForeignKeep, major, minor int) (flags int, set bool, err error) { - if k == 0 { - return 0, false, nil - } - if major < 8 || (major == 8 && minor < 15) { - return 0, false, errKeepUnsupported - } - if unknown := k &^ (ForeignKeepAll | ForeignKeepNone); unknown != 0 { - return 0, false, fmt.Errorf("unknown ForeignKeep bits: %#x", int(unknown)) - } - k &^= ForeignKeepNone - if major == 8 && minor < 18 { - // libvips before 8.18 doesn't know VIPS_FOREIGN_KEEP_GAINMAP. - k &^= ForeignKeepGainmap - } - return int(k), true, nil -} - -// applyKeep validates k against the running libvips and stores it in p. -// Every save-param builder calls it, so the buffer and streaming paths -// share one version guard. -func applyKeep(p *C.struct_SaveParams, k ForeignKeep) error { - flags, set, err := resolveKeep(k, MajorVersion, MinorVersion) - if errors.Is(err, errKeepUnsupported) { - return fmt.Errorf("Keep requires libvips 8.15+, found %s", Version) - } - if err != nil { - return err - } - p.keep = C.int(flags) - p.keepSet = C.int(boolToInt(set)) - return nil -} - -// ImageType represents an image type -type ImageType int - -// ImageType enum -const ( - ImageTypeUnknown ImageType = C.UNKNOWN - ImageTypeGIF ImageType = C.GIF - ImageTypeJPEG ImageType = C.JPEG - ImageTypeMagick ImageType = C.MAGICK - ImageTypePDF ImageType = C.PDF - ImageTypePNG ImageType = C.PNG - ImageTypeSVG ImageType = C.SVG - ImageTypeTIFF ImageType = C.TIFF - ImageTypeWEBP ImageType = C.WEBP - ImageTypeHEIF ImageType = C.HEIF - ImageTypeBMP ImageType = C.BMP - ImageTypeAVIF ImageType = C.AVIF - ImageTypeJP2K ImageType = C.JP2K - ImageTypeJXL ImageType = C.JXL - ImageTypePSD ImageType = C.PSD -) - -// Types which should be deligated to ImageMagick loader -var imageMagickTypes = map[ImageType]bool{ - ImageTypeBMP: true, - ImageTypePSD: true, -} - -var imageTypeExtensionMap = map[ImageType]string{ - ImageTypeGIF: ".gif", - ImageTypeJPEG: ".jpeg", - ImageTypeMagick: ".magick", - ImageTypePDF: ".pdf", - ImageTypePNG: ".png", - ImageTypeSVG: ".svg", - ImageTypeTIFF: ".tiff", - ImageTypeWEBP: ".webp", - ImageTypeHEIF: ".heic", - ImageTypeBMP: ".bmp", - ImageTypeAVIF: ".avif", - ImageTypeJP2K: ".jp2", - ImageTypeJXL: ".jxl", - ImageTypePSD: ".psd", -} - -// ImageTypes defines the various image types supported by govips -var ImageTypes = map[ImageType]string{ - ImageTypeGIF: "gif", - ImageTypeJPEG: "jpeg", - ImageTypeMagick: "magick", - ImageTypePDF: "pdf", - ImageTypePNG: "png", - ImageTypeSVG: "svg", - ImageTypeTIFF: "tiff", - ImageTypeWEBP: "webp", - ImageTypeHEIF: "heif", - ImageTypeBMP: "bmp", - ImageTypeAVIF: "heif", - ImageTypeJP2K: "jp2k", - ImageTypeJXL: "jxl", - ImageTypePSD: "psd", -} - -// TiffCompression represents method for compressing a tiff at export -type TiffCompression int - -// TiffCompression enum -const ( - TiffCompressionNone TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_NONE - TiffCompressionJpeg TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_JPEG - TiffCompressionDeflate TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_DEFLATE - TiffCompressionPackbits TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_PACKBITS - TiffCompressionFax4 TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_CCITTFAX4 - TiffCompressionLzw TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_LZW - TiffCompressionWebp TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_WEBP - TiffCompressionZstd TiffCompression = C.VIPS_FOREIGN_TIFF_COMPRESSION_ZSTD -) - -// TiffPredictor represents method for compressing a tiff at export -type TiffPredictor int - -// TiffPredictor enum -const ( - TiffPredictorNone TiffPredictor = C.VIPS_FOREIGN_TIFF_PREDICTOR_NONE - TiffPredictorHorizontal TiffPredictor = C.VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL - TiffPredictorFloat TiffPredictor = C.VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT -) - -// PngFilter represents filter algorithms that can be applied before compression. -// See https://www.w3.org/TR/PNG-Filters.html -type PngFilter int - -// PngFilter enum -const ( - PngFilterNone PngFilter = C.VIPS_FOREIGN_PNG_FILTER_NONE - PngFilterSub PngFilter = C.VIPS_FOREIGN_PNG_FILTER_SUB - PngFilterUo PngFilter = C.VIPS_FOREIGN_PNG_FILTER_UP - PngFilterAvg PngFilter = C.VIPS_FOREIGN_PNG_FILTER_AVG - PngFilterPaeth PngFilter = C.VIPS_FOREIGN_PNG_FILTER_PAETH - PngFilterAll PngFilter = C.VIPS_FOREIGN_PNG_FILTER_ALL -) - -// Access represents how libvips opens files. -// See https://www.libvips.org/API/current/How-it-opens-files.html -const ( - AccessRandom int = C.VIPS_ACCESS_RANDOM - AccessSequential int = C.VIPS_ACCESS_SEQUENTIAL - AccessSequentialUnbuffered int = C.VIPS_ACCESS_SEQUENTIAL_UNBUFFERED - AccessLast int = C.VIPS_ACCESS_LAST -) - -// FileExt returns the canonical extension for the ImageType -func (i ImageType) FileExt() string { - if ext, ok := imageTypeExtensionMap[i]; ok { - return ext - } - return "" -} - -// IsTypeSupported checks whether given image type is supported by govips -func IsTypeSupported(imageType ImageType) bool { - if err := startupIfNeeded(); err != nil { - govipsLog("govips", LogLevelError, fmt.Sprintf("failed to start vips: %v", err)) - return false - } - - // BMP is supported via the magick loader - if imageType == ImageTypeBMP { - return supportedImageTypes[ImageTypeMagick] - } - - return supportedImageTypes[imageType] -} - -// DetermineImageType attempts to determine the image type of the given buffer -func DetermineImageType(buf []byte) ImageType { - if len(buf) < 12 { - return ImageTypeUnknown - } else if isJPEG(buf) { - return ImageTypeJPEG - } else if isPNG(buf) { - return ImageTypePNG - } else if isGIF(buf) { - return ImageTypeGIF - } else if isTIFF(buf) { - return ImageTypeTIFF - } else if isWEBP(buf) { - return ImageTypeWEBP - } else if isAVIF(buf) { - return ImageTypeAVIF - } else if isHEIF(buf) { - return ImageTypeHEIF - } else if isSVG(buf) { - return ImageTypeSVG - } else if isBMP(buf) { - return ImageTypeBMP - } else if isJP2K(buf) { - return ImageTypeJP2K - } else if isJXL(buf) { - return ImageTypeJXL - } else if isPDF(buf) { - return ImageTypePDF - } else if isICO(buf) { - return ImageTypeMagick - } else if isPSD(buf) { - return ImageTypePSD - } else { - return ImageTypeUnknown - } -} - -var jpeg = []byte("\xFF\xD8\xFF") - -func isJPEG(buf []byte) bool { - return bytes.HasPrefix(buf, jpeg) -} - -var gifHeader = []byte("\x47\x49\x46") - -func isGIF(buf []byte) bool { - return bytes.HasPrefix(buf, gifHeader) -} - -var pngHeader = []byte("\x89\x50\x4E\x47") - -func isPNG(buf []byte) bool { - return bytes.HasPrefix(buf, pngHeader) -} - -var tifII = []byte("\x49\x49\x2A\x00") -var tifMM = []byte("\x4D\x4D\x00\x2A") -var bigTifII = []byte("\x49\x49\x2B\x00") -var bigTifMM = []byte("\x4D\x4D\x00\x2B") - -func isTIFF(buf []byte) bool { - return bytes.HasPrefix(buf, tifII) || - bytes.HasPrefix(buf, tifMM) || - bytes.HasPrefix(buf, bigTifII) || - bytes.HasPrefix(buf, bigTifMM) -} - -var webpHeader = []byte("\x57\x45\x42\x50") - -func isWEBP(buf []byte) bool { - return bytes.Equal(buf[8:12], webpHeader) -} - -// https://github.com/strukturag/libheif/blob/master/libheif/heif.cc -var ftyp = []byte("ftyp") -var heic = []byte("heic") -var heix = []byte("heix") -var heim = []byte("heim") -var heis = []byte("heis") -var mif1 = []byte("mif1") -var msf1 = []byte("msf1") -var avif = []byte("avif") -var avis = []byte("avis") - -func isHEIF(buf []byte) bool { - return bytes.Equal(buf[4:8], ftyp) && (bytes.Equal(buf[8:12], heic) || - bytes.Equal(buf[8:12], heix) || - bytes.Equal(buf[8:12], heim) || - bytes.Equal(buf[8:12], heis) || - bytes.Equal(buf[8:12], mif1) || - bytes.Equal(buf[8:12], msf1)) || - isAVIF(buf) -} - -func isAVIF(buf []byte) bool { - return bytes.Equal(buf[4:8], ftyp) && - (bytes.Equal(buf[8:12], avif) || bytes.Equal(buf[8:12], avis)) -} - -var svg = []byte("= 2 && buf[0] == 0xFF && buf[1] == 0x0A { - return true - } - if len(buf) >= 8 && bytes.Equal(buf[4:8], []byte("JXL ")) { - return true - } - return false -} - -var icoHeader = []byte("\x00\x00\x01\x00") - -func isICO(buf []byte) bool { - return bytes.HasPrefix(buf, icoHeader) -} - -var psdHeader = []byte("\x38\x42\x50\x53") - -func isPSD(buf []byte) bool { - return bytes.HasPrefix(buf, psdHeader) -} - -func isNeedToChangeLoaderToMagick(t ImageType) bool { - return imageMagickTypes[t] -} - -func vipsLoadFromBuffer(buf []byte, params *ImportParams) (*C.VipsImage, ImageType, ImageType, error) { - src := buf - // Reference src here so it's not garbage collected during image initialization. - defer runtime.KeepAlive(src) - - originalType := DetermineImageType(src) - currentType := originalType - - // Map image types which are not supported by libvips itself to ImageMagick - if isNeedToChangeLoaderToMagick(originalType) { - currentType = ImageTypeMagick - } - - if !IsTypeSupported(currentType) { - govipsLog("govips", LogLevelInfo, fmt.Sprintf("failed to understand image format size=%d", len(src))) - return nil, currentType, originalType, ErrUnsupportedImageFormat - } - - importParams := createImportParams(currentType, params) - - if err := C.load_from_buffer(&importParams, unsafe.Pointer(&src[0]), C.size_t(len(src))); err != 0 { - return nil, currentType, originalType, handleImageError(importParams.outputImage) - } - - return importParams.outputImage, currentType, originalType, nil -} - -func maybeSetBoolParam(p BoolParameter, cp *C.Param) { - if p.IsSet() { - C.set_bool_param(cp, toGboolean(p.Get())) - } -} - -func maybeSetIntParam(p IntParameter, cp *C.Param) { - if p.IsSet() { - C.set_int_param(cp, C.int(p.Get())) - } -} - -func maybeSetDoubleParam(p Float64Parameter, cp *C.Param) { - if p.IsSet() { - C.set_double_param(cp, C.gdouble(p.Get())) - } -} - -func createImportParams(format ImageType, params *ImportParams) C.LoadParams { - p := C.create_load_params(C.ImageType(format)) - - maybeSetBoolParam(params.AutoRotate, &p.autorotate) - maybeSetBoolParam(params.FailOnError, &p.fail) - maybeSetIntParam(params.Page, &p.page) - maybeSetIntParam(params.NumPages, &p.n) - maybeSetIntParam(params.JpegShrinkFactor, &p.jpegShrink) - maybeSetDoubleParam(params.WebpScaleFactor, &p.webpScale) - maybeSetBoolParam(params.HeifThumbnail, &p.heifThumbnail) - maybeSetBoolParam(params.SvgUnlimited, &p.svgUnlimited) - maybeSetIntParam(params.Access, &p.access) - - if params.Density.IsSet() { - C.set_double_param(&p.dpi, C.gdouble(params.Density.Get())) - } - return p -} - -func newSaveParamsJPEG(in *C.VipsImage, params JpegExportParams) (C.struct_SaveParams, error) { - p := C.create_save_params(C.JPEG) - p.inputImage = in - p.stripMetadata = C.int(boolToInt(params.StripMetadata)) - p.quality = C.int(params.Quality) - p.interlace = C.int(boolToInt(params.Interlace)) - p.jpegOptimizeCoding = C.int(boolToInt(params.OptimizeCoding)) - p.jpegSubsample = C.VipsForeignSubsample(params.SubsampleMode) - p.jpegTrellisQuant = C.int(boolToInt(params.TrellisQuant)) - p.jpegOvershootDeringing = C.int(boolToInt(params.OvershootDeringing)) - p.jpegOptimizeScans = C.int(boolToInt(params.OptimizeScans)) - p.jpegQuantTable = C.int(params.QuantTable) - if err := applyKeep(&p, params.Keep); err != nil { - return p, err - } - return p, nil -} - -func vipsSaveJPEGToBuffer(in *C.VipsImage, params JpegExportParams) ([]byte, error) { - incOpCounter("save_jpeg_buffer") - - p, err := newSaveParamsJPEG(in, params) - if err != nil { - return nil, err - } - return vipsSaveToBuffer(p) -} - -func newSaveParamsPNG(in *C.VipsImage, params PngExportParams) (C.struct_SaveParams, error) { - p := C.create_save_params(C.PNG) - p.inputImage = in - p.quality = C.int(params.Quality) - p.stripMetadata = C.int(boolToInt(params.StripMetadata)) - p.interlace = C.int(boolToInt(params.Interlace)) - p.pngCompression = C.int(params.Compression) - p.pngFilter = C.VipsForeignPngFilter(params.Filter) - p.pngPalette = C.int(boolToInt(params.Palette)) - p.pngDither = C.double(params.Dither) - p.pngBitdepth = C.int(params.Bitdepth) - if err := applyKeep(&p, params.Keep); err != nil { - return p, err - } - return p, nil -} - -func vipsSavePNGToBuffer(in *C.VipsImage, params PngExportParams) ([]byte, error) { - incOpCounter("save_png_buffer") - - p, err := newSaveParamsPNG(in, params) - if err != nil { - return nil, err - } - return vipsSaveToBuffer(p) -} - -// newSaveParamsWebP returns the populated params and a cleanup function -// that must be called once the save has completed; it frees the ICC -// profile C string, if one was allocated. Both the buffer and streaming -// WebP savers go through here, so the TargetSize version guard covers -// both paths. -func newSaveParamsWebP(in *C.VipsImage, params WebpExportParams) (C.struct_SaveParams, func(), error) { - noop := func() {} - p := C.create_save_params(C.WEBP) - p.inputImage = in - p.stripMetadata = C.int(boolToInt(params.StripMetadata)) - p.quality = C.int(params.Quality) - p.webpLossless = C.int(boolToInt(params.Lossless)) - p.webpNearLossless = C.int(boolToInt(params.NearLossless)) - p.webpReductionEffort = C.int(params.ReductionEffort) - p.webpMinSize = C.int(boolToInt(params.MinSize)) - p.webpKMin = C.int(params.MinKeyFrames) - p.webpKMax = C.int(params.MaxKeyFrames) - - if params.TargetSize > 0 { - // webpsave's "target_size" property was added in libvips 8.17.4; setting - // it on an older libvips fails at the C layer with an opaque "no property - // named `target_size'" error. Fail clearly instead. - if MajorVersion < 8 || (MajorVersion == 8 && MinorVersion < 17) || - (MajorVersion == 8 && MinorVersion == 17 && MicroVersion < 4) { - return p, noop, fmt.Errorf("WebpExportParams.TargetSize requires libvips 8.17.4+, found %s", Version) - } - p.webpTargetSize = C.int(params.TargetSize) - } - - if err := applyKeep(&p, params.Keep); err != nil { - return p, noop, err - } - - iccProfile := params.IccProfile - if p.keepSet != 0 && ForeignKeep(p.keep)&ForeignKeepIcc == 0 { - // An explicit Keep without ICC wins over any profile: libvips - // would otherwise embed a supplied profile regardless of keep. - iccProfile = "" - } - - cleanup := noop - if iccProfile != "" { - p.webpIccProfile = C.CString(iccProfile) - profile := p.webpIccProfile - cleanup = func() { C.free(unsafe.Pointer(profile)) } - } - return p, cleanup, nil -} - -func vipsSaveWebPToBuffer(in *C.VipsImage, params WebpExportParams) ([]byte, error) { - incOpCounter("save_webp_buffer") - - p, cleanup, err := newSaveParamsWebP(in, params) - if err != nil { - return nil, err - } - defer cleanup() - - return vipsSaveToBuffer(p) -} - -func newSaveParamsTIFF(in *C.VipsImage, params TiffExportParams) (C.struct_SaveParams, error) { - p := C.create_save_params(C.TIFF) - p.inputImage = in - p.stripMetadata = C.int(boolToInt(params.StripMetadata)) - p.quality = C.int(params.Quality) - p.tiffCompression = C.VipsForeignTiffCompression(params.Compression) - p.tiffPyramid = C.int(boolToInt(params.Pyramid)) - p.tiffTile = C.int(boolToInt(params.Tile)) - tileHeight := params.TileHeight - tileWidth := params.TileWidth - if tileHeight <= 0 { - tileHeight = 256 - } - if tileWidth <= 0 { - tileWidth = 256 - } - p.tiffTileHeight = C.int(tileHeight) - p.tiffTileWidth = C.int(tileWidth) - if err := applyKeep(&p, params.Keep); err != nil { - return p, err - } - return p, nil -} - -func vipsSaveTIFFToBuffer(in *C.VipsImage, params TiffExportParams) ([]byte, error) { - incOpCounter("save_tiff_buffer") - - p, err := newSaveParamsTIFF(in, params) - if err != nil { - return nil, err - } - return vipsSaveToBuffer(p) -} - -func newSaveParamsHEIF(in *C.VipsImage, params HeifExportParams) (C.struct_SaveParams, error) { - p := C.create_save_params(C.HEIF) - p.inputImage = in - p.outputFormat = C.HEIF - p.quality = C.int(params.Quality) - p.heifLossless = C.int(boolToInt(params.Lossless)) - p.heifBitdepth = C.int(params.Bitdepth) - p.heifEffort = C.int(params.Effort) - if err := applyKeep(&p, params.Keep); err != nil { - return p, err - } - return p, nil -} - -func vipsSaveHEIFToBuffer(in *C.VipsImage, params HeifExportParams) ([]byte, error) { - incOpCounter("save_heif_buffer") - - p, err := newSaveParamsHEIF(in, params) - if err != nil { - return nil, err - } - return vipsSaveToBuffer(p) -} - -func vipsSaveAVIFToBuffer(in *C.VipsImage, params AvifExportParams) ([]byte, error) { - incOpCounter("save_heif_buffer") - - // Speed was deprecated but we want to avoid breaking code that still uses it: - effort := params.Effort - if params.Speed != 0 { - effort = params.Speed - } - - p := C.create_save_params(C.AVIF) - p.inputImage = in - p.stripMetadata = C.int(boolToInt(params.StripMetadata)) - p.outputFormat = C.AVIF - p.quality = C.int(params.Quality) - p.heifLossless = C.int(boolToInt(params.Lossless)) - p.heifBitdepth = C.int(params.Bitdepth) - p.heifEffort = C.int(effort) - if err := applyKeep(&p, params.Keep); err != nil { - return nil, err - } - - return vipsSaveToBuffer(p) -} - -func vipsSaveJP2KToBuffer(in *C.VipsImage, params Jp2kExportParams) ([]byte, error) { - incOpCounter("save_jp2k_buffer") - - p := C.create_save_params(C.JP2K) - p.inputImage = in - p.outputFormat = C.JP2K - p.quality = C.int(params.Quality) - p.jp2kLossless = C.int(boolToInt(params.Lossless)) - p.jp2kTileWidth = C.int(params.TileWidth) - p.jp2kTileHeight = C.int(params.TileHeight) - p.jpegSubsample = C.VipsForeignSubsample(params.SubsampleMode) - if err := applyKeep(&p, params.Keep); err != nil { - return nil, err - } - - return vipsSaveToBuffer(p) -} - -func newSaveParamsGIF(in *C.VipsImage, params GifExportParams) (C.struct_SaveParams, error) { - p := C.create_save_params(C.GIF) - p.inputImage = in - p.quality = C.int(params.Quality) - p.gifDither = C.double(params.Dither) - p.gifEffort = C.int(params.Effort) - p.gifBitdepth = C.int(params.Bitdepth) - if err := applyKeep(&p, params.Keep); err != nil { - return p, err - } - return p, nil -} - -func vipsSaveGIFToBuffer(in *C.VipsImage, params GifExportParams) ([]byte, error) { - incOpCounter("save_gif_buffer") - - p, err := newSaveParamsGIF(in, params) - if err != nil { - return nil, err - } - return vipsSaveToBuffer(p) -} - -func vipsSaveJxlToBuffer(in *C.VipsImage, params JxlExportParams) ([]byte, error) { - incOpCounter("save_jxl_buffer") - - p := C.create_save_params(C.JXL) - p.inputImage = in - p.outputFormat = C.JXL - p.quality = C.int(params.Quality) - p.jxlLossless = C.int(boolToInt(params.Lossless)) - p.jxlTier = C.int(params.Tier) - p.jxlDistance = C.double(params.Distance) - p.jxlEffort = C.int(params.Effort) - if err := applyKeep(&p, params.Keep); err != nil { - return nil, err - } - - return vipsSaveToBuffer(p) -} - -func vipsSaveMagickToBuffer(in *C.VipsImage, params MagickExportParams) ([]byte, error) { - incOpCounter("save_magick_buffer") - - if params.Format == "" { - return nil, errors.New("magick format required") - } - p := C.create_save_params(C.MAGICK) - p.inputImage = in - p.outputFormat = C.MAGICK - p.quality = C.int(params.Quality) - // libvips copies the string into the operation; nothing else frees it. - cFormat := C.CString(params.Format) - defer freeCString(cFormat) - p.magickFormat = cFormat - p.magickOptimizeGifFrames = C.int(boolToInt(params.OptimizeGifFrames)) - p.magickOptimizeGifTransparency = C.int(boolToInt(params.OptimizeGifTransparency)) - p.magickBitDepth = C.int(params.BitDepth) - if err := applyKeep(&p, params.Keep); err != nil { - return nil, err - } - - return vipsSaveToBuffer(p) -} - -func vipsSaveToBuffer(params C.struct_SaveParams) ([]byte, error) { - if err := C.save_to_buffer(¶ms); err != 0 { - return nil, handleSaveBufferError(params.outputBuffer) - } - - buf := C.GoBytes(params.outputBuffer, C.int(params.outputLen)) - defer gFreePointer(params.outputBuffer) - - return buf, nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.h b/vendor/github.com/davidbyttow/govips/v2/vips/foreign.h deleted file mode 100644 index d22619ca44..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/foreign.h +++ /dev/null @@ -1,155 +0,0 @@ -// https://libvips.github.io/libvips/API/current/VipsForeignSave.html - -// clang-format off -// include order matters -#include - -#include -#include -// clang-format n - -#ifndef BOOL -#define BOOL int -#endif - -typedef enum types { - UNKNOWN = 0, - JPEG, - WEBP, - PNG, - TIFF, - GIF, - PDF, - SVG, - MAGICK, - HEIF, - BMP, - AVIF, - JP2K, - JXL, - PSD, -} ImageType; - -typedef enum ParamType { - PARAM_TYPE_NULL, - PARAM_TYPE_BOOL, - PARAM_TYPE_INT, - PARAM_TYPE_DOUBLE, -} ParamType; - -typedef struct Param { - ParamType type; - - union Value { - gboolean b; - gint i; - gdouble d; - } value; - - gboolean is_set; - -} Param; - -void set_bool_param(Param *p, gboolean b); -void set_int_param(Param *p, gint i); -void set_double_param(Param *p, gdouble d); - -typedef struct LoadParams { - ImageType inputFormat; - VipsBlob *inputBlob; - VipsImage *outputImage; - - Param autorotate; - Param fail; - Param page; - Param n; - Param dpi; - Param jpegShrink; - Param webpScale; - Param heifThumbnail; - Param svgUnlimited; - Param access; - -} LoadParams; - -LoadParams create_load_params(ImageType inputFormat); -int load_from_buffer(LoadParams *params, void *buf, size_t len); - -typedef struct SaveParams { - VipsImage *inputImage; - void *outputBuffer; - ImageType outputFormat; - size_t outputLen; - - BOOL stripMetadata; - // libvips "keep" flags (VipsForeignKeep, 8.15+). Plain int so the header - // still compiles against libvips 8.14; only applied when keepSet. - int keep; - BOOL keepSet; - int quality; - BOOL interlace; - - // JPEG - BOOL jpegOptimizeCoding; - VipsForeignSubsample jpegSubsample; - BOOL jpegTrellisQuant; - BOOL jpegOvershootDeringing; - BOOL jpegOptimizeScans; - int jpegQuantTable; - - // PNG - int pngCompression; - VipsForeignPngFilter pngFilter; - BOOL pngPalette; - double pngDither; - int pngBitdepth; - - // GIF (with CGIF) - double gifDither; - int gifEffort; - int gifBitdepth; - - // WEBP - BOOL webpLossless; - BOOL webpNearLossless; - int webpReductionEffort; - char *webpIccProfile; - BOOL webpMinSize; - int webpKMin; - int webpKMax; - int webpTargetSize; - - // HEIF - https://github.com/libvips/libvips/blob/master/libvips/foreign/heifsave.c#L71 - int heifBitdepth; // Bitdepth to save at for >8 bit images - BOOL heifLossless; // Lossless compression - int heifEffort; // CPU effort (0 - 9) - - // TIFF - VipsForeignTiffCompression tiffCompression; - VipsForeignTiffPredictor tiffPredictor; - BOOL tiffPyramid; - BOOL tiffTile; - int tiffTileHeight; - int tiffTileWidth; - - // JPEG2000 - BOOL jp2kLossless; - int jp2kTileWidth; - int jp2kTileHeight; - - // JXL - int jxlTier; - double jxlDistance; - int jxlEffort; - BOOL jxlLossless; - - // MAGICK - char *magickFormat; - BOOL magickOptimizeGifFrames; - BOOL magickOptimizeGifTransparency; - int magickBitDepth; -} SaveParams; - -SaveParams create_save_params(ImageType outputFormat); -int save_to_buffer(SaveParams *params); - diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/gen_enum_extras.go b/vendor/github.com/davidbyttow/govips/v2/vips/gen_enum_extras.go deleted file mode 100644 index 2e739a82fd..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/gen_enum_extras.go +++ /dev/null @@ -1,139 +0,0 @@ -// Code generated by vipsgen. DO NOT EDIT. -// -// Enum types needed by generated code that are not yet defined in the -// hand-written codebase. These will move to gen_enums.go in Phase 4. - -package vips - -// #include -import "C" - -// Precision represents VipsPrecision for controlling computation precision. -type Precision int - -const ( - PrecisionInteger Precision = C.VIPS_PRECISION_INTEGER - PrecisionFloat Precision = C.VIPS_PRECISION_FLOAT - PrecisionApproximate Precision = C.VIPS_PRECISION_APPROXIMATE -) - -// Combine represents VipsCombine for combining operations. -type Combine int - -const ( - CombineMax Combine = C.VIPS_COMBINE_MAX - CombineSum Combine = C.VIPS_COMBINE_SUM - CombineMin Combine = C.VIPS_COMBINE_MIN -) - -// CombineMode represents VipsCombineMode for draw combine operations. -type CombineMode int - -const ( - CombineModeSet CombineMode = C.VIPS_COMBINE_MODE_SET - CombineModeAdd CombineMode = C.VIPS_COMBINE_MODE_ADD -) - -// OperationBoolean represents VipsOperationBoolean for boolean operations. -type OperationBoolean int - -const ( - OperationBooleanAnd OperationBoolean = C.VIPS_OPERATION_BOOLEAN_AND - OperationBooleanOr OperationBoolean = C.VIPS_OPERATION_BOOLEAN_OR - OperationBooleanEor OperationBoolean = C.VIPS_OPERATION_BOOLEAN_EOR - OperationBooleanLshift OperationBoolean = C.VIPS_OPERATION_BOOLEAN_LSHIFT - OperationBooleanRshift OperationBoolean = C.VIPS_OPERATION_BOOLEAN_RSHIFT -) - -// OperationComplex represents VipsOperationComplex for complex operations. -type OperationComplex int - -const ( - OperationComplexPolar OperationComplex = C.VIPS_OPERATION_COMPLEX_POLAR - OperationComplexRect OperationComplex = C.VIPS_OPERATION_COMPLEX_RECT - OperationComplexConj OperationComplex = C.VIPS_OPERATION_COMPLEX_CONJ -) - -// OperationComplex2 represents VipsOperationComplex2 for binary complex operations. -type OperationComplex2 int - -const ( - OperationComplex2CrossPhase OperationComplex2 = C.VIPS_OPERATION_COMPLEX2_CROSS_PHASE -) - -// OperationComplexget represents VipsOperationComplexget for getting complex components. -type OperationComplexget int - -const ( - OperationComplexgetReal OperationComplexget = C.VIPS_OPERATION_COMPLEXGET_REAL - OperationComplexgetImag OperationComplexget = C.VIPS_OPERATION_COMPLEXGET_IMAG -) - -// OperationMath represents VipsOperationMath for math operations. -type OperationMath int - -const ( - OperationMathSin OperationMath = C.VIPS_OPERATION_MATH_SIN - OperationMathCos OperationMath = C.VIPS_OPERATION_MATH_COS - OperationMathTan OperationMath = C.VIPS_OPERATION_MATH_TAN - OperationMathAsin OperationMath = C.VIPS_OPERATION_MATH_ASIN - OperationMathAcos OperationMath = C.VIPS_OPERATION_MATH_ACOS - OperationMathAtan OperationMath = C.VIPS_OPERATION_MATH_ATAN - OperationMathLog OperationMath = C.VIPS_OPERATION_MATH_LOG - OperationMathLog10 OperationMath = C.VIPS_OPERATION_MATH_LOG10 - OperationMathExp OperationMath = C.VIPS_OPERATION_MATH_EXP - OperationMathExp10 OperationMath = C.VIPS_OPERATION_MATH_EXP10 -) - -// OperationMath2 represents VipsOperationMath2 for binary math operations. -type OperationMath2 int - -const ( - OperationMath2Pow OperationMath2 = C.VIPS_OPERATION_MATH2_POW - OperationMath2Wop OperationMath2 = C.VIPS_OPERATION_MATH2_WOP - OperationMath2Atan2 OperationMath2 = C.VIPS_OPERATION_MATH2_ATAN2 -) - -// OperationRelational represents VipsOperationRelational for relational operations. -type OperationRelational int - -const ( - OperationRelationalEqual OperationRelational = C.VIPS_OPERATION_RELATIONAL_EQUAL - OperationRelationalNoteq OperationRelational = C.VIPS_OPERATION_RELATIONAL_NOTEQ - OperationRelationalLess OperationRelational = C.VIPS_OPERATION_RELATIONAL_LESS - OperationRelationalLesseq OperationRelational = C.VIPS_OPERATION_RELATIONAL_LESSEQ - OperationRelationalMore OperationRelational = C.VIPS_OPERATION_RELATIONAL_MORE - OperationRelationalMoreeq OperationRelational = C.VIPS_OPERATION_RELATIONAL_MOREEQ -) - -// OperationRound represents VipsOperationRound for rounding operations. -type OperationRound int - -const ( - OperationRoundRint OperationRound = C.VIPS_OPERATION_ROUND_RINT - OperationRoundCeil OperationRound = C.VIPS_OPERATION_ROUND_CEIL - OperationRoundFloor OperationRound = C.VIPS_OPERATION_ROUND_FLOOR -) - -// OperationMorphology represents VipsOperationMorphology for morphological operations. -type OperationMorphology int - -const ( - OperationMorphologyErode OperationMorphology = C.VIPS_OPERATION_MORPHOLOGY_ERODE - OperationMorphologyDilate OperationMorphology = C.VIPS_OPERATION_MORPHOLOGY_DILATE -) - -// FailOn represents VipsFailOn for controlling error handling on load. -type FailOn int - -const ( - FailOnNone FailOn = C.VIPS_FAIL_ON_NONE - FailOnTruncated FailOn = C.VIPS_FAIL_ON_TRUNCATED - FailOnError FailOn = C.VIPS_FAIL_ON_ERROR - FailOnWarning FailOn = C.VIPS_FAIL_ON_WARNING -) - -// ForeignKeep represents VipsForeignKeep flags for controlling metadata retention. -type ForeignKeep int - -// Note: ForeignKeep is a flags (bitmask) type. Values combined with |. diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/generate.go b/vendor/github.com/davidbyttow/govips/v2/vips/generate.go deleted file mode 100644 index 52c946aae9..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package vips - -//go:generate go run ../cmd/vipsgen --generate --output=. diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/generated.c b/vendor/github.com/davidbyttow/govips/v2/vips/generated.c deleted file mode 100644 index c981daa4c2..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/generated.c +++ /dev/null @@ -1,5228 +0,0 @@ -// Code generated by vipsgen. DO NOT EDIT. -#include "generated.h" - -int gen_vips_CMC2LCh(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("CMC2LCh"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_CMYK2XYZ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("CMYK2XYZ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_HSV2sRGB(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("HSV2sRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LCh2CMC(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LCh2CMC"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LCh2Lab(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LCh2Lab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Lab2LCh(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Lab2LCh"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Lab2LabQ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Lab2LabQ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Lab2LabS(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Lab2LabS"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Lab2XYZ(VipsImage * input, VipsImage ** out_out, GenLab2XYZOpts *opts) { - VipsOperation *op = vips_operation_new("Lab2XYZ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_temp) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->temp, opts->temp_n); - vips_object_set(VIPS_OBJECT(op), "temp", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LabQ2Lab(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LabQ2Lab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LabQ2LabS(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LabQ2LabS"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LabQ2sRGB(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LabQ2sRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LabS2Lab(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LabS2Lab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_LabS2LabQ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("LabS2LabQ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Oklab2Oklch(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Oklab2Oklch"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Oklab2XYZ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Oklab2XYZ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Oklch2Oklab(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Oklch2Oklab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_XYZ2CMYK(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("XYZ2CMYK"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_XYZ2Lab(VipsImage * input, VipsImage ** out_out, GenXYZ2LabOpts *opts) { - VipsOperation *op = vips_operation_new("XYZ2Lab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_temp) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->temp, opts->temp_n); - vips_object_set(VIPS_OBJECT(op), "temp", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_XYZ2Oklab(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("XYZ2Oklab"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_XYZ2Yxy(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("XYZ2Yxy"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_XYZ2scRGB(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("XYZ2scRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_Yxy2XYZ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("Yxy2XYZ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_abs(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("abs"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_add(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("add"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_affine(VipsImage * input, double * matrix, int matrix_n, VipsImage ** out_out, GenAffineOpts *opts) { - VipsOperation *op = vips_operation_new("affine"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(matrix, matrix_n); - int ret = vips_object_set(VIPS_OBJECT(op), "matrix", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (opts) { - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - if (opts->has_oarea) { - { - VipsArrayInt *arr = vips_array_int_new(opts->oarea, opts->oarea_n); - vips_object_set(VIPS_OBJECT(op), "oarea", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_odx) { - vips_object_set(VIPS_OBJECT(op), "odx", opts->odx, NULL); - } - if (opts->has_ody) { - vips_object_set(VIPS_OBJECT(op), "ody", opts->ody, NULL); - } - if (opts->has_idx) { - vips_object_set(VIPS_OBJECT(op), "idx", opts->idx, NULL); - } - if (opts->has_idy) { - vips_object_set(VIPS_OBJECT(op), "idy", opts->idy, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_premultiplied) { - vips_object_set(VIPS_OBJECT(op), "premultiplied", (gboolean)opts->premultiplied, NULL); - } - if (opts->has_extend) { - vips_object_set(VIPS_OBJECT(op), "extend", (int)opts->extend, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_arrayjoin(VipsImage **input, int input_n, VipsImage ** out_out, GenArrayjoinOpts *opts) { - VipsOperation *op = vips_operation_new("arrayjoin"); - if (!op) return -1; - - { - VipsArrayImage *arr = vips_array_image_new(input, input_n); - int ret = vips_object_set(VIPS_OBJECT(op), "in", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (opts) { - if (opts->has_across) { - vips_object_set(VIPS_OBJECT(op), "across", opts->across, NULL); - } - if (opts->has_shim) { - vips_object_set(VIPS_OBJECT(op), "shim", opts->shim, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_halign) { - vips_object_set(VIPS_OBJECT(op), "halign", (int)opts->halign, NULL); - } - if (opts->has_valign) { - vips_object_set(VIPS_OBJECT(op), "valign", (int)opts->valign, NULL); - } - if (opts->has_hspacing) { - vips_object_set(VIPS_OBJECT(op), "hspacing", opts->hspacing, NULL); - } - if (opts->has_vspacing) { - vips_object_set(VIPS_OBJECT(op), "vspacing", opts->vspacing, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_autorot(VipsImage * input, VipsImage ** out_out, int * out_angle, int * out_flip) { - VipsOperation *op = vips_operation_new("autorot"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - g_object_get(VIPS_OBJECT(op), "angle", out_angle, NULL); - g_object_get(VIPS_OBJECT(op), "flip", out_flip, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_avg(VipsImage * input, double * out_out) { - VipsOperation *op = vips_operation_new("avg"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandbool(VipsImage * input, VipsOperationBoolean boolean, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("bandbool"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "boolean", (int)boolean, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandfold(VipsImage * input, VipsImage ** out_out, GenBandfoldOpts *opts) { - VipsOperation *op = vips_operation_new("bandfold"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_factor) { - vips_object_set(VIPS_OBJECT(op), "factor", opts->factor, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandjoin(VipsImage **input, int input_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("bandjoin"); - if (!op) return -1; - - { - VipsArrayImage *arr = vips_array_image_new(input, input_n); - int ret = vips_object_set(VIPS_OBJECT(op), "in", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandjoin_const(VipsImage * input, double * c, int c_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("bandjoin_const"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(c, c_n); - int ret = vips_object_set(VIPS_OBJECT(op), "c", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandmean(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("bandmean"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandrank(VipsImage **input, int input_n, VipsImage ** out_out, GenBandrankOpts *opts) { - VipsOperation *op = vips_operation_new("bandrank"); - if (!op) return -1; - - { - VipsArrayImage *arr = vips_array_image_new(input, input_n); - int ret = vips_object_set(VIPS_OBJECT(op), "in", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (opts) { - if (opts->has_index) { - vips_object_set(VIPS_OBJECT(op), "index", opts->index, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_bandunfold(VipsImage * input, VipsImage ** out_out, GenBandunfoldOpts *opts) { - VipsOperation *op = vips_operation_new("bandunfold"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_factor) { - vips_object_set(VIPS_OBJECT(op), "factor", opts->factor, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_black(int width, int height, VipsImage ** out_out, GenBlackOpts *opts) { - VipsOperation *op = vips_operation_new("black"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_bands) { - vips_object_set(VIPS_OBJECT(op), "bands", opts->bands, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_boolean(VipsImage * left, VipsImage * right, VipsOperationBoolean boolean, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("boolean"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "boolean", (int)boolean, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_boolean_const(VipsImage * input, VipsOperationBoolean boolean, double * c, int c_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("boolean_const"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "boolean", (int)boolean, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(c, c_n); - int ret = vips_object_set(VIPS_OBJECT(op), "c", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_buildlut(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("buildlut"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_byteswap(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("byteswap"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_cache(VipsImage * input, VipsImage ** out_out, GenCacheOpts *opts) { - VipsOperation *op = vips_operation_new("cache"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_maxTiles) { - vips_object_set(VIPS_OBJECT(op), "max-tiles", opts->maxTiles, NULL); - } - if (opts->has_tileHeight) { - vips_object_set(VIPS_OBJECT(op), "tile-height", opts->tileHeight, NULL); - } - if (opts->has_tileWidth) { - vips_object_set(VIPS_OBJECT(op), "tile-width", opts->tileWidth, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_canny(VipsImage * input, VipsImage ** out_out, GenCannyOpts *opts) { - VipsOperation *op = vips_operation_new("canny"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_sigma) { - vips_object_set(VIPS_OBJECT(op), "sigma", opts->sigma, NULL); - } - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_cast(VipsImage * input, VipsBandFormat format, VipsImage ** out_out, GenCastOpts *opts) { - VipsOperation *op = vips_operation_new("cast"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "format", (int)format, NULL)) goto error; - - if (opts) { - if (opts->has_shift) { - vips_object_set(VIPS_OBJECT(op), "shift", (gboolean)opts->shift, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_clamp(VipsImage * input, VipsImage ** out_out, GenClampOpts *opts) { - VipsOperation *op = vips_operation_new("clamp"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_min) { - vips_object_set(VIPS_OBJECT(op), "min", opts->min, NULL); - } - if (opts->has_max) { - vips_object_set(VIPS_OBJECT(op), "max", opts->max, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_compass(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenCompassOpts *opts) { - VipsOperation *op = vips_operation_new("compass"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (opts) { - if (opts->has_times) { - vips_object_set(VIPS_OBJECT(op), "times", opts->times, NULL); - } - if (opts->has_angle) { - vips_object_set(VIPS_OBJECT(op), "angle", (int)opts->angle, NULL); - } - if (opts->has_combine) { - vips_object_set(VIPS_OBJECT(op), "combine", (int)opts->combine, NULL); - } - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - if (opts->has_layers) { - vips_object_set(VIPS_OBJECT(op), "layers", opts->layers, NULL); - } - if (opts->has_cluster) { - vips_object_set(VIPS_OBJECT(op), "cluster", opts->cluster, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_complex(VipsImage * input, VipsOperationComplex cmplx, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("complex"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "cmplx", (int)cmplx, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_complex2(VipsImage * left, VipsImage * right, VipsOperationComplex2 cmplx, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("complex2"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "cmplx", (int)cmplx, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_complexform(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("complexform"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_complexget(VipsImage * input, VipsOperationComplexget get, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("complexget"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "get", (int)get, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_composite2(VipsImage * base, VipsImage * overlay, VipsBlendMode mode, VipsImage ** out_out, GenComposite2Opts *opts) { - VipsOperation *op = vips_operation_new("composite2"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "base", base, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "overlay", overlay, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mode", (int)mode, NULL)) goto error; - - if (opts) { - if (opts->has_x) { - vips_object_set(VIPS_OBJECT(op), "x", opts->x, NULL); - } - if (opts->has_y) { - vips_object_set(VIPS_OBJECT(op), "y", opts->y, NULL); - } - if (opts->has_compositingSpace) { - vips_object_set(VIPS_OBJECT(op), "compositing-space", (int)opts->compositingSpace, NULL); - } - if (opts->has_premultiplied) { - vips_object_set(VIPS_OBJECT(op), "premultiplied", (gboolean)opts->premultiplied, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_conv(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvOpts *opts) { - VipsOperation *op = vips_operation_new("conv"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (opts) { - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - if (opts->has_layers) { - vips_object_set(VIPS_OBJECT(op), "layers", opts->layers, NULL); - } - if (opts->has_cluster) { - vips_object_set(VIPS_OBJECT(op), "cluster", opts->cluster, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_conva(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvaOpts *opts) { - VipsOperation *op = vips_operation_new("conva"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (opts) { - if (opts->has_layers) { - vips_object_set(VIPS_OBJECT(op), "layers", opts->layers, NULL); - } - if (opts->has_cluster) { - vips_object_set(VIPS_OBJECT(op), "cluster", opts->cluster, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_convasep(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvasepOpts *opts) { - VipsOperation *op = vips_operation_new("convasep"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (opts) { - if (opts->has_layers) { - vips_object_set(VIPS_OBJECT(op), "layers", opts->layers, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_convf(VipsImage * input, VipsImage * mask, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("convf"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_convi(VipsImage * input, VipsImage * mask, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("convi"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_convsep(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvsepOpts *opts) { - VipsOperation *op = vips_operation_new("convsep"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (opts) { - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - if (opts->has_layers) { - vips_object_set(VIPS_OBJECT(op), "layers", opts->layers, NULL); - } - if (opts->has_cluster) { - vips_object_set(VIPS_OBJECT(op), "cluster", opts->cluster, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_copy(VipsImage * input, VipsImage ** out_out, GenCopyOpts *opts) { - VipsOperation *op = vips_operation_new("copy"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_width) { - vips_object_set(VIPS_OBJECT(op), "width", opts->width, NULL); - } - if (opts->has_height) { - vips_object_set(VIPS_OBJECT(op), "height", opts->height, NULL); - } - if (opts->has_bands) { - vips_object_set(VIPS_OBJECT(op), "bands", opts->bands, NULL); - } - if (opts->has_format) { - vips_object_set(VIPS_OBJECT(op), "format", (int)opts->format, NULL); - } - if (opts->has_coding) { - vips_object_set(VIPS_OBJECT(op), "coding", (int)opts->coding, NULL); - } - if (opts->has_interpretation) { - vips_object_set(VIPS_OBJECT(op), "interpretation", (int)opts->interpretation, NULL); - } - if (opts->has_xres) { - vips_object_set(VIPS_OBJECT(op), "xres", opts->xres, NULL); - } - if (opts->has_yres) { - vips_object_set(VIPS_OBJECT(op), "yres", opts->yres, NULL); - } - if (opts->has_xoffset) { - vips_object_set(VIPS_OBJECT(op), "xoffset", opts->xoffset, NULL); - } - if (opts->has_yoffset) { - vips_object_set(VIPS_OBJECT(op), "yoffset", opts->yoffset, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_countlines(VipsImage * input, VipsDirection direction, double * out_nolines) { - VipsOperation *op = vips_operation_new("countlines"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "nolines", out_nolines, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_dE00(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("dE00"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_dE76(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("dE76"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_dECMC(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("dECMC"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_deviate(VipsImage * input, double * out_out) { - VipsOperation *op = vips_operation_new("deviate"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_divide(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("divide"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_extract_area(VipsImage * input, int left, int top, int width, int height, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("extract_area"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "input", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "top", top, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_extract_band(VipsImage * input, int band, VipsImage ** out_out, GenExtractBandOpts *opts) { - VipsOperation *op = vips_operation_new("extract_band"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "band", band, NULL)) goto error; - - if (opts) { - if (opts->has_n) { - vips_object_set(VIPS_OBJECT(op), "n", opts->n, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_eye(int width, int height, VipsImage ** out_out, GenEyeOpts *opts) { - VipsOperation *op = vips_operation_new("eye"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_factor) { - vips_object_set(VIPS_OBJECT(op), "factor", opts->factor, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_falsecolour(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("falsecolour"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_fastcor(VipsImage * input, VipsImage * ref, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("fastcor"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_fill_nearest(VipsImage * input, VipsImage ** out_out, VipsImage ** out_distance) { - VipsOperation *op = vips_operation_new("fill_nearest"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - g_object_get(VIPS_OBJECT(op), "distance", out_distance, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_flatten(VipsImage * input, VipsImage ** out_out, GenFlattenOpts *opts) { - VipsOperation *op = vips_operation_new("flatten"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_maxAlpha) { - vips_object_set(VIPS_OBJECT(op), "max-alpha", opts->maxAlpha, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_flip(VipsImage * input, VipsDirection direction, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("flip"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_float2rad(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("float2rad"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_fractsurf(int width, int height, double fractalDimension, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("fractsurf"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "fractal-dimension", fractalDimension, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_freqmult(VipsImage * input, VipsImage * mask, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("freqmult"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_fwfft(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("fwfft"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_gamma(VipsImage * input, VipsImage ** out_out, GenGammaOpts *opts) { - VipsOperation *op = vips_operation_new("gamma"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_exponent) { - vips_object_set(VIPS_OBJECT(op), "exponent", opts->exponent, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_gaussblur(VipsImage * input, double sigma, VipsImage ** out_out, GenGaussblurOpts *opts) { - VipsOperation *op = vips_operation_new("gaussblur"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sigma", sigma, NULL)) goto error; - - if (opts) { - if (opts->has_minAmpl) { - vips_object_set(VIPS_OBJECT(op), "min-ampl", opts->minAmpl, NULL); - } - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_gaussmat(double sigma, double minAmpl, VipsImage ** out_out, GenGaussmatOpts *opts) { - VipsOperation *op = vips_operation_new("gaussmat"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "sigma", sigma, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "min-ampl", minAmpl, NULL)) goto error; - - if (opts) { - if (opts->has_separable) { - vips_object_set(VIPS_OBJECT(op), "separable", (gboolean)opts->separable, NULL); - } - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_gaussnoise(int width, int height, VipsImage ** out_out, GenGaussnoiseOpts *opts) { - VipsOperation *op = vips_operation_new("gaussnoise"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_sigma) { - vips_object_set(VIPS_OBJECT(op), "sigma", opts->sigma, NULL); - } - if (opts->has_mean) { - vips_object_set(VIPS_OBJECT(op), "mean", opts->mean, NULL); - } - if (opts->has_seed) { - vips_object_set(VIPS_OBJECT(op), "seed", opts->seed, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_globalbalance(VipsImage * input, VipsImage ** out_out, GenGlobalbalanceOpts *opts) { - VipsOperation *op = vips_operation_new("globalbalance"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_gamma) { - vips_object_set(VIPS_OBJECT(op), "gamma", opts->gamma, NULL); - } - if (opts->has_intOutput) { - vips_object_set(VIPS_OBJECT(op), "int-output", (gboolean)opts->intOutput, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_gravity(VipsImage * input, VipsCompassDirection direction, int width, int height, VipsImage ** out_out, GenGravityOpts *opts) { - VipsOperation *op = vips_operation_new("gravity"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_extend) { - vips_object_set(VIPS_OBJECT(op), "extend", (int)opts->extend, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_grey(int width, int height, VipsImage ** out_out, GenGreyOpts *opts) { - VipsOperation *op = vips_operation_new("grey"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_grid(VipsImage * input, int tileHeight, int across, int down, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("grid"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "tile-height", tileHeight, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "across", across, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "down", down, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_cum(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("hist_cum"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_entropy(VipsImage * input, double * out_out) { - VipsOperation *op = vips_operation_new("hist_entropy"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_equal(VipsImage * input, VipsImage ** out_out, GenHistEqualOpts *opts) { - VipsOperation *op = vips_operation_new("hist_equal"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_band) { - vips_object_set(VIPS_OBJECT(op), "band", opts->band, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_find(VipsImage * input, VipsImage ** out_out, GenHistFindOpts *opts) { - VipsOperation *op = vips_operation_new("hist_find"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_band) { - vips_object_set(VIPS_OBJECT(op), "band", opts->band, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_find_indexed(VipsImage * input, VipsImage * index, VipsImage ** out_out, GenHistFindIndexedOpts *opts) { - VipsOperation *op = vips_operation_new("hist_find_indexed"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "index", index, NULL)) goto error; - - if (opts) { - if (opts->has_combine) { - vips_object_set(VIPS_OBJECT(op), "combine", (int)opts->combine, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_find_ndim(VipsImage * input, VipsImage ** out_out, GenHistFindNdimOpts *opts) { - VipsOperation *op = vips_operation_new("hist_find_ndim"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_bins) { - vips_object_set(VIPS_OBJECT(op), "bins", opts->bins, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_ismonotonic(VipsImage * input, int * out_monotonic) { - VipsOperation *op = vips_operation_new("hist_ismonotonic"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "monotonic", out_monotonic, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_local(VipsImage * input, int width, int height, VipsImage ** out_out, GenHistLocalOpts *opts) { - VipsOperation *op = vips_operation_new("hist_local"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_maxSlope) { - vips_object_set(VIPS_OBJECT(op), "max-slope", opts->maxSlope, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_match(VipsImage * input, VipsImage * ref, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("hist_match"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_norm(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("hist_norm"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hist_plot(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("hist_plot"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hough_circle(VipsImage * input, VipsImage ** out_out, GenHoughCircleOpts *opts) { - VipsOperation *op = vips_operation_new("hough_circle"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_scale) { - vips_object_set(VIPS_OBJECT(op), "scale", opts->scale, NULL); - } - if (opts->has_minRadius) { - vips_object_set(VIPS_OBJECT(op), "min-radius", opts->minRadius, NULL); - } - if (opts->has_maxRadius) { - vips_object_set(VIPS_OBJECT(op), "max-radius", opts->maxRadius, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_hough_line(VipsImage * input, VipsImage ** out_out, GenHoughLineOpts *opts) { - VipsOperation *op = vips_operation_new("hough_line"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_width) { - vips_object_set(VIPS_OBJECT(op), "width", opts->width, NULL); - } - if (opts->has_height) { - vips_object_set(VIPS_OBJECT(op), "height", opts->height, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_icc_export(VipsImage * input, VipsImage ** out_out, GenIccExportOpts *opts) { - VipsOperation *op = vips_operation_new("icc_export"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_pcs) { - vips_object_set(VIPS_OBJECT(op), "pcs", (int)opts->pcs, NULL); - } - if (opts->has_intent) { - vips_object_set(VIPS_OBJECT(op), "intent", (int)opts->intent, NULL); - } - if (opts->has_blackPointCompensation) { - vips_object_set(VIPS_OBJECT(op), "black-point-compensation", (gboolean)opts->blackPointCompensation, NULL); - } - if (opts->has_outputProfile) { - vips_object_set(VIPS_OBJECT(op), "output-profile", opts->outputProfile, NULL); - } - if (opts->has_depth) { - vips_object_set(VIPS_OBJECT(op), "depth", opts->depth, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_icc_import(VipsImage * input, VipsImage ** out_out, GenIccImportOpts *opts) { - VipsOperation *op = vips_operation_new("icc_import"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_pcs) { - vips_object_set(VIPS_OBJECT(op), "pcs", (int)opts->pcs, NULL); - } - if (opts->has_intent) { - vips_object_set(VIPS_OBJECT(op), "intent", (int)opts->intent, NULL); - } - if (opts->has_blackPointCompensation) { - vips_object_set(VIPS_OBJECT(op), "black-point-compensation", (gboolean)opts->blackPointCompensation, NULL); - } - if (opts->has_embedded) { - vips_object_set(VIPS_OBJECT(op), "embedded", (gboolean)opts->embedded, NULL); - } - if (opts->has_inputProfile) { - vips_object_set(VIPS_OBJECT(op), "input-profile", opts->inputProfile, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_identity(VipsImage ** out_out, GenIdentityOpts *opts) { - VipsOperation *op = vips_operation_new("identity"); - if (!op) return -1; - - - if (opts) { - if (opts->has_bands) { - vips_object_set(VIPS_OBJECT(op), "bands", opts->bands, NULL); - } - if (opts->has_ushort) { - vips_object_set(VIPS_OBJECT(op), "ushort", (gboolean)opts->ushort, NULL); - } - if (opts->has_size) { - vips_object_set(VIPS_OBJECT(op), "size", opts->size, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_ifthenelse(VipsImage * cond, VipsImage * in1, VipsImage * in2, VipsImage ** out_out, GenIfthenelseOpts *opts) { - VipsOperation *op = vips_operation_new("ifthenelse"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "cond", cond, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "in1", in1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "in2", in2, NULL)) goto error; - - if (opts) { - if (opts->has_blend) { - vips_object_set(VIPS_OBJECT(op), "blend", (gboolean)opts->blend, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_insert(VipsImage * main, VipsImage * sub, int x, int y, VipsImage ** out_out, GenInsertOpts *opts) { - VipsOperation *op = vips_operation_new("insert"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "main", main, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sub", sub, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "x", x, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "y", y, NULL)) goto error; - - if (opts) { - if (opts->has_expand) { - vips_object_set(VIPS_OBJECT(op), "expand", (gboolean)opts->expand, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_invert(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("invert"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_invertlut(VipsImage * input, VipsImage ** out_out, GenInvertlutOpts *opts) { - VipsOperation *op = vips_operation_new("invertlut"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_size) { - vips_object_set(VIPS_OBJECT(op), "size", opts->size, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_invfft(VipsImage * input, VipsImage ** out_out, GenInvfftOpts *opts) { - VipsOperation *op = vips_operation_new("invfft"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_real) { - vips_object_set(VIPS_OBJECT(op), "real", (gboolean)opts->real, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_join(VipsImage * in1, VipsImage * in2, VipsDirection direction, VipsImage ** out_out, GenJoinOpts *opts) { - VipsOperation *op = vips_operation_new("join"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in1", in1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "in2", in2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - - if (opts) { - if (opts->has_expand) { - vips_object_set(VIPS_OBJECT(op), "expand", (gboolean)opts->expand, NULL); - } - if (opts->has_shim) { - vips_object_set(VIPS_OBJECT(op), "shim", opts->shim, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_align) { - vips_object_set(VIPS_OBJECT(op), "align", (int)opts->align, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_labelregions(VipsImage * input, VipsImage ** out_mask, int * out_segments) { - VipsOperation *op = vips_operation_new("labelregions"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "mask", out_mask, NULL); - g_object_get(VIPS_OBJECT(op), "segments", out_segments, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_linear(VipsImage * input, double * a, int a_n, double * b, int b_n, VipsImage ** out_out, GenLinearOpts *opts) { - VipsOperation *op = vips_operation_new("linear"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(a, a_n); - int ret = vips_object_set(VIPS_OBJECT(op), "a", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - { - VipsArrayDouble *arr = vips_array_double_new(b, b_n); - int ret = vips_object_set(VIPS_OBJECT(op), "b", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_linecache(VipsImage * input, VipsImage ** out_out, GenLinecacheOpts *opts) { - VipsOperation *op = vips_operation_new("linecache"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_tileHeight) { - vips_object_set(VIPS_OBJECT(op), "tile-height", opts->tileHeight, NULL); - } - if (opts->has_access) { - vips_object_set(VIPS_OBJECT(op), "access", (int)opts->access, NULL); - } - if (opts->has_threaded) { - vips_object_set(VIPS_OBJECT(op), "threaded", (gboolean)opts->threaded, NULL); - } - if (opts->has_persistent) { - vips_object_set(VIPS_OBJECT(op), "persistent", (gboolean)opts->persistent, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_logmat(double sigma, double minAmpl, VipsImage ** out_out, GenLogmatOpts *opts) { - VipsOperation *op = vips_operation_new("logmat"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "sigma", sigma, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "min-ampl", minAmpl, NULL)) goto error; - - if (opts) { - if (opts->has_separable) { - vips_object_set(VIPS_OBJECT(op), "separable", (gboolean)opts->separable, NULL); - } - if (opts->has_precision) { - vips_object_set(VIPS_OBJECT(op), "precision", (int)opts->precision, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mapim(VipsImage * input, VipsImage * index, VipsImage ** out_out, GenMapimOpts *opts) { - VipsOperation *op = vips_operation_new("mapim"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "index", index, NULL)) goto error; - - if (opts) { - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_premultiplied) { - vips_object_set(VIPS_OBJECT(op), "premultiplied", (gboolean)opts->premultiplied, NULL); - } - if (opts->has_extend) { - vips_object_set(VIPS_OBJECT(op), "extend", (int)opts->extend, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_maplut(VipsImage * input, VipsImage * lut, VipsImage ** out_out, GenMaplutOpts *opts) { - VipsOperation *op = vips_operation_new("maplut"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "lut", lut, NULL)) goto error; - - if (opts) { - if (opts->has_band) { - vips_object_set(VIPS_OBJECT(op), "band", opts->band, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_butterworth(int width, int height, double order, double frequencyCutoff, double amplitudeCutoff, VipsImage ** out_out, GenMaskButterworthOpts *opts) { - VipsOperation *op = vips_operation_new("mask_butterworth"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "order", order, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_butterworth_band(int width, int height, double order, double frequencyCutoffX, double frequencyCutoffY, double radius, double amplitudeCutoff, VipsImage ** out_out, GenMaskButterworthBandOpts *opts) { - VipsOperation *op = vips_operation_new("mask_butterworth_band"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "order", order, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-x", frequencyCutoffX, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-y", frequencyCutoffY, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "radius", radius, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_butterworth_ring(int width, int height, double order, double frequencyCutoff, double amplitudeCutoff, double ringwidth, VipsImage ** out_out, GenMaskButterworthRingOpts *opts) { - VipsOperation *op = vips_operation_new("mask_butterworth_ring"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "order", order, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ringwidth", ringwidth, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_fractal(int width, int height, double fractalDimension, VipsImage ** out_out, GenMaskFractalOpts *opts) { - VipsOperation *op = vips_operation_new("mask_fractal"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "fractal-dimension", fractalDimension, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_gaussian(int width, int height, double frequencyCutoff, double amplitudeCutoff, VipsImage ** out_out, GenMaskGaussianOpts *opts) { - VipsOperation *op = vips_operation_new("mask_gaussian"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_gaussian_band(int width, int height, double frequencyCutoffX, double frequencyCutoffY, double radius, double amplitudeCutoff, VipsImage ** out_out, GenMaskGaussianBandOpts *opts) { - VipsOperation *op = vips_operation_new("mask_gaussian_band"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-x", frequencyCutoffX, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-y", frequencyCutoffY, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "radius", radius, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_gaussian_ring(int width, int height, double frequencyCutoff, double amplitudeCutoff, double ringwidth, VipsImage ** out_out, GenMaskGaussianRingOpts *opts) { - VipsOperation *op = vips_operation_new("mask_gaussian_ring"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "amplitude-cutoff", amplitudeCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ringwidth", ringwidth, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_ideal(int width, int height, double frequencyCutoff, VipsImage ** out_out, GenMaskIdealOpts *opts) { - VipsOperation *op = vips_operation_new("mask_ideal"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_ideal_band(int width, int height, double frequencyCutoffX, double frequencyCutoffY, double radius, VipsImage ** out_out, GenMaskIdealBandOpts *opts) { - VipsOperation *op = vips_operation_new("mask_ideal_band"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-x", frequencyCutoffX, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff-y", frequencyCutoffY, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "radius", radius, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mask_ideal_ring(int width, int height, double frequencyCutoff, double ringwidth, VipsImage ** out_out, GenMaskIdealRingOpts *opts) { - VipsOperation *op = vips_operation_new("mask_ideal_ring"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "frequency-cutoff", frequencyCutoff, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ringwidth", ringwidth, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_nodc) { - vips_object_set(VIPS_OBJECT(op), "nodc", (gboolean)opts->nodc, NULL); - } - if (opts->has_reject) { - vips_object_set(VIPS_OBJECT(op), "reject", (gboolean)opts->reject, NULL); - } - if (opts->has_optical) { - vips_object_set(VIPS_OBJECT(op), "optical", (gboolean)opts->optical, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_match(VipsImage * ref, VipsImage * sec, int xr1, int yr1, int xs1, int ys1, int xr2, int yr2, int xs2, int ys2, VipsImage ** out_out, GenMatchOpts *opts) { - VipsOperation *op = vips_operation_new("match"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sec", sec, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xr1", xr1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yr1", yr1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xs1", xs1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ys1", ys1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xr2", xr2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yr2", yr2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xs2", xs2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ys2", ys2, NULL)) goto error; - - if (opts) { - if (opts->has_hwindow) { - vips_object_set(VIPS_OBJECT(op), "hwindow", opts->hwindow, NULL); - } - if (opts->has_harea) { - vips_object_set(VIPS_OBJECT(op), "harea", opts->harea, NULL); - } - if (opts->has_search) { - vips_object_set(VIPS_OBJECT(op), "search", (gboolean)opts->search, NULL); - } - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_math(VipsImage * input, VipsOperationMath math, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("math"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "math", (int)math, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_math2(VipsImage * left, VipsImage * right, VipsOperationMath2 math2, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("math2"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "math2", (int)math2, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_math2_const(VipsImage * input, VipsOperationMath2 math2, double * c, int c_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("math2_const"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "math2", (int)math2, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(c, c_n); - int ret = vips_object_set(VIPS_OBJECT(op), "c", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_matrixinvert(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("matrixinvert"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_matrixmultiply(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("matrixmultiply"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_maxpair(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("maxpair"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_merge(VipsImage * ref, VipsImage * sec, VipsDirection direction, int dx, int dy, VipsImage ** out_out, GenMergeOpts *opts) { - VipsOperation *op = vips_operation_new("merge"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sec", sec, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "dx", dx, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "dy", dy, NULL)) goto error; - - if (opts) { - if (opts->has_mblend) { - vips_object_set(VIPS_OBJECT(op), "mblend", opts->mblend, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_minpair(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("minpair"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_morph(VipsImage * input, VipsImage * mask, VipsOperationMorphology morph, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("morph"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "mask", mask, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "morph", (int)morph, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mosaic(VipsImage * ref, VipsImage * sec, VipsDirection direction, int xref, int yref, int xsec, int ysec, VipsImage ** out_out, int * out_dx0, int * out_dy0, double * out_scale1, double * out_angle1, double * out_dy1, double * out_dx1, GenMosaicOpts *opts) { - VipsOperation *op = vips_operation_new("mosaic"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sec", sec, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xref", xref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yref", yref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xsec", xsec, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ysec", ysec, NULL)) goto error; - - if (opts) { - if (opts->has_hwindow) { - vips_object_set(VIPS_OBJECT(op), "hwindow", opts->hwindow, NULL); - } - if (opts->has_harea) { - vips_object_set(VIPS_OBJECT(op), "harea", opts->harea, NULL); - } - if (opts->has_mblend) { - vips_object_set(VIPS_OBJECT(op), "mblend", opts->mblend, NULL); - } - if (opts->has_bandno) { - vips_object_set(VIPS_OBJECT(op), "bandno", opts->bandno, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - g_object_get(VIPS_OBJECT(op), "dx0", out_dx0, NULL); - g_object_get(VIPS_OBJECT(op), "dy0", out_dy0, NULL); - g_object_get(VIPS_OBJECT(op), "scale1", out_scale1, NULL); - g_object_get(VIPS_OBJECT(op), "angle1", out_angle1, NULL); - g_object_get(VIPS_OBJECT(op), "dy1", out_dy1, NULL); - g_object_get(VIPS_OBJECT(op), "dx1", out_dx1, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_mosaic1(VipsImage * ref, VipsImage * sec, VipsDirection direction, int xr1, int yr1, int xs1, int ys1, int xr2, int yr2, int xs2, int ys2, VipsImage ** out_out, GenMosaic1Opts *opts) { - VipsOperation *op = vips_operation_new("mosaic1"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "sec", sec, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "direction", (int)direction, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xr1", xr1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yr1", yr1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xs1", xs1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ys1", ys1, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xr2", xr2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yr2", yr2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xs2", xs2, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ys2", ys2, NULL)) goto error; - - if (opts) { - if (opts->has_hwindow) { - vips_object_set(VIPS_OBJECT(op), "hwindow", opts->hwindow, NULL); - } - if (opts->has_harea) { - vips_object_set(VIPS_OBJECT(op), "harea", opts->harea, NULL); - } - if (opts->has_search) { - vips_object_set(VIPS_OBJECT(op), "search", (gboolean)opts->search, NULL); - } - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - if (opts->has_mblend) { - vips_object_set(VIPS_OBJECT(op), "mblend", opts->mblend, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_msb(VipsImage * input, VipsImage ** out_out, GenMsbOpts *opts) { - VipsOperation *op = vips_operation_new("msb"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_band) { - vips_object_set(VIPS_OBJECT(op), "band", opts->band, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_multiply(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("multiply"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_percent(VipsImage * input, double percent, int * out_threshold) { - VipsOperation *op = vips_operation_new("percent"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "percent", percent, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "threshold", out_threshold, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_perlin(int width, int height, VipsImage ** out_out, GenPerlinOpts *opts) { - VipsOperation *op = vips_operation_new("perlin"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_cellSize) { - vips_object_set(VIPS_OBJECT(op), "cell-size", opts->cellSize, NULL); - } - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_seed) { - vips_object_set(VIPS_OBJECT(op), "seed", opts->seed, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_phasecor(VipsImage * input, VipsImage * in2, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("phasecor"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "in2", in2, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_premultiply(VipsImage * input, VipsImage ** out_out, GenPremultiplyOpts *opts) { - VipsOperation *op = vips_operation_new("premultiply"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_maxAlpha) { - vips_object_set(VIPS_OBJECT(op), "max-alpha", opts->maxAlpha, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_prewitt(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("prewitt"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_profile(VipsImage * input, VipsImage ** out_columns, VipsImage ** out_rows) { - VipsOperation *op = vips_operation_new("profile"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "columns", out_columns, NULL); - g_object_get(VIPS_OBJECT(op), "rows", out_rows, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_project(VipsImage * input, VipsImage ** out_columns, VipsImage ** out_rows) { - VipsOperation *op = vips_operation_new("project"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "columns", out_columns, NULL); - g_object_get(VIPS_OBJECT(op), "rows", out_rows, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_quadratic(VipsImage * input, VipsImage * coeff, VipsImage ** out_out, GenQuadraticOpts *opts) { - VipsOperation *op = vips_operation_new("quadratic"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "coeff", coeff, NULL)) goto error; - - if (opts) { - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_rad2float(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("rad2float"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_rank(VipsImage * input, int width, int height, int index, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("rank"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "index", index, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_recomb(VipsImage * input, VipsImage * m, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("recomb"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "m", m, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_reduce(VipsImage * input, double hshrink, double vshrink, VipsImage ** out_out, GenReduceOpts *opts) { - VipsOperation *op = vips_operation_new("reduce"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "hshrink", hshrink, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "vshrink", vshrink, NULL)) goto error; - - if (opts) { - if (opts->has_kernel) { - vips_object_set(VIPS_OBJECT(op), "kernel", (int)opts->kernel, NULL); - } - if (opts->has_gap) { - vips_object_set(VIPS_OBJECT(op), "gap", opts->gap, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_reduceh(VipsImage * input, double hshrink, VipsImage ** out_out, GenReducehOpts *opts) { - VipsOperation *op = vips_operation_new("reduceh"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "hshrink", hshrink, NULL)) goto error; - - if (opts) { - if (opts->has_kernel) { - vips_object_set(VIPS_OBJECT(op), "kernel", (int)opts->kernel, NULL); - } - if (opts->has_gap) { - vips_object_set(VIPS_OBJECT(op), "gap", opts->gap, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_reducev(VipsImage * input, double vshrink, VipsImage ** out_out, GenReducevOpts *opts) { - VipsOperation *op = vips_operation_new("reducev"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "vshrink", vshrink, NULL)) goto error; - - if (opts) { - if (opts->has_kernel) { - vips_object_set(VIPS_OBJECT(op), "kernel", (int)opts->kernel, NULL); - } - if (opts->has_gap) { - vips_object_set(VIPS_OBJECT(op), "gap", opts->gap, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_relational(VipsImage * left, VipsImage * right, VipsOperationRelational relational, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("relational"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "relational", (int)relational, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_relational_const(VipsImage * input, VipsOperationRelational relational, double * c, int c_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("relational_const"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "relational", (int)relational, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(c, c_n); - int ret = vips_object_set(VIPS_OBJECT(op), "c", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_remainder(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("remainder"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_remainder_const(VipsImage * input, double * c, int c_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("remainder_const"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - { - VipsArrayDouble *arr = vips_array_double_new(c, c_n); - int ret = vips_object_set(VIPS_OBJECT(op), "c", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_remosaic(VipsImage * input, const char * oldStr, const char * newStr, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("remosaic"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "old-str", oldStr, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "new-str", newStr, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_replicate(VipsImage * input, int across, int down, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("replicate"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "across", across, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "down", down, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_rot(VipsImage * input, VipsAngle angle, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("rot"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "angle", (int)angle, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_rot45(VipsImage * input, VipsImage ** out_out, GenRot45Opts *opts) { - VipsOperation *op = vips_operation_new("rot45"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_angle) { - vips_object_set(VIPS_OBJECT(op), "angle", (int)opts->angle, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_rotate(VipsImage * input, double angle, VipsImage ** out_out, GenRotateOpts *opts) { - VipsOperation *op = vips_operation_new("rotate"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "angle", angle, NULL)) goto error; - - if (opts) { - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_odx) { - vips_object_set(VIPS_OBJECT(op), "odx", opts->odx, NULL); - } - if (opts->has_ody) { - vips_object_set(VIPS_OBJECT(op), "ody", opts->ody, NULL); - } - if (opts->has_idx) { - vips_object_set(VIPS_OBJECT(op), "idx", opts->idx, NULL); - } - if (opts->has_idy) { - vips_object_set(VIPS_OBJECT(op), "idy", opts->idy, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_round(VipsImage * input, VipsOperationRound round, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("round"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "round", (int)round, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sRGB2HSV(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("sRGB2HSV"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sRGB2scRGB(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("sRGB2scRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_scRGB2BW(VipsImage * input, VipsImage ** out_out, GenScRGB2BWOpts *opts) { - VipsOperation *op = vips_operation_new("scRGB2BW"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_depth) { - vips_object_set(VIPS_OBJECT(op), "depth", opts->depth, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_scRGB2XYZ(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("scRGB2XYZ"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_scRGB2sRGB(VipsImage * input, VipsImage ** out_out, GenScRGB2sRGBOpts *opts) { - VipsOperation *op = vips_operation_new("scRGB2sRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_depth) { - vips_object_set(VIPS_OBJECT(op), "depth", opts->depth, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_scale(VipsImage * input, VipsImage ** out_out, GenScaleOpts *opts) { - VipsOperation *op = vips_operation_new("scale"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_exp) { - vips_object_set(VIPS_OBJECT(op), "exp", opts->exp, NULL); - } - if (opts->has_log) { - vips_object_set(VIPS_OBJECT(op), "log", (gboolean)opts->log, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_scharr(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("scharr"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sequential(VipsImage * input, VipsImage ** out_out, GenSequentialOpts *opts) { - VipsOperation *op = vips_operation_new("sequential"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_tileHeight) { - vips_object_set(VIPS_OBJECT(op), "tile-height", opts->tileHeight, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sharpen(VipsImage * input, VipsImage ** out_out, GenSharpenOpts *opts) { - VipsOperation *op = vips_operation_new("sharpen"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_sigma) { - vips_object_set(VIPS_OBJECT(op), "sigma", opts->sigma, NULL); - } - if (opts->has_x1) { - vips_object_set(VIPS_OBJECT(op), "x1", opts->x1, NULL); - } - if (opts->has_y2) { - vips_object_set(VIPS_OBJECT(op), "y2", opts->y2, NULL); - } - if (opts->has_y3) { - vips_object_set(VIPS_OBJECT(op), "y3", opts->y3, NULL); - } - if (opts->has_m1) { - vips_object_set(VIPS_OBJECT(op), "m1", opts->m1, NULL); - } - if (opts->has_m2) { - vips_object_set(VIPS_OBJECT(op), "m2", opts->m2, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_shrink(VipsImage * input, double hshrink, double vshrink, VipsImage ** out_out, GenShrinkOpts *opts) { - VipsOperation *op = vips_operation_new("shrink"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "hshrink", hshrink, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "vshrink", vshrink, NULL)) goto error; - - if (opts) { - if (opts->has_ceil) { - vips_object_set(VIPS_OBJECT(op), "ceil", (gboolean)opts->ceil, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_shrinkh(VipsImage * input, int hshrink, VipsImage ** out_out, GenShrinkhOpts *opts) { - VipsOperation *op = vips_operation_new("shrinkh"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "hshrink", hshrink, NULL)) goto error; - - if (opts) { - if (opts->has_ceil) { - vips_object_set(VIPS_OBJECT(op), "ceil", (gboolean)opts->ceil, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_shrinkv(VipsImage * input, int vshrink, VipsImage ** out_out, GenShrinkvOpts *opts) { - VipsOperation *op = vips_operation_new("shrinkv"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "vshrink", vshrink, NULL)) goto error; - - if (opts) { - if (opts->has_ceil) { - vips_object_set(VIPS_OBJECT(op), "ceil", (gboolean)opts->ceil, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sign(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("sign"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_similarity(VipsImage * input, VipsImage ** out_out, GenSimilarityOpts *opts) { - VipsOperation *op = vips_operation_new("similarity"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_scale) { - vips_object_set(VIPS_OBJECT(op), "scale", opts->scale, NULL); - } - if (opts->has_angle) { - vips_object_set(VIPS_OBJECT(op), "angle", opts->angle, NULL); - } - if (opts->has_interpolate) { - vips_object_set(VIPS_OBJECT(op), "interpolate", opts->interpolate, NULL); - } - if (opts->has_background) { - { - VipsArrayDouble *arr = vips_array_double_new(opts->background, opts->background_n); - vips_object_set(VIPS_OBJECT(op), "background", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - } - } - if (opts->has_odx) { - vips_object_set(VIPS_OBJECT(op), "odx", opts->odx, NULL); - } - if (opts->has_ody) { - vips_object_set(VIPS_OBJECT(op), "ody", opts->ody, NULL); - } - if (opts->has_idx) { - vips_object_set(VIPS_OBJECT(op), "idx", opts->idx, NULL); - } - if (opts->has_idy) { - vips_object_set(VIPS_OBJECT(op), "idy", opts->idy, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sines(int width, int height, VipsImage ** out_out, GenSinesOpts *opts) { - VipsOperation *op = vips_operation_new("sines"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - if (opts->has_hfreq) { - vips_object_set(VIPS_OBJECT(op), "hfreq", opts->hfreq, NULL); - } - if (opts->has_vfreq) { - vips_object_set(VIPS_OBJECT(op), "vfreq", opts->vfreq, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_smartcrop(VipsImage * input, int width, int height, int * out_attentionX, VipsImage ** out_out, int * out_attentionY, GenSmartcropOpts *opts) { - VipsOperation *op = vips_operation_new("smartcrop"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "input", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_interesting) { - vips_object_set(VIPS_OBJECT(op), "interesting", (int)opts->interesting, NULL); - } - if (opts->has_premultiplied) { - vips_object_set(VIPS_OBJECT(op), "premultiplied", (gboolean)opts->premultiplied, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "attention-x", out_attentionX, NULL); - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - g_object_get(VIPS_OBJECT(op), "attention-y", out_attentionY, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sobel(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("sobel"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_spcor(VipsImage * input, VipsImage * ref, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("spcor"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "ref", ref, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_spectrum(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("spectrum"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_stats(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("stats"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_stdif(VipsImage * input, int width, int height, VipsImage ** out_out, GenStdifOpts *opts) { - VipsOperation *op = vips_operation_new("stdif"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_s0) { - vips_object_set(VIPS_OBJECT(op), "s0", opts->s0, NULL); - } - if (opts->has_b) { - vips_object_set(VIPS_OBJECT(op), "b", opts->b, NULL); - } - if (opts->has_m0) { - vips_object_set(VIPS_OBJECT(op), "m0", opts->m0, NULL); - } - if (opts->has_a) { - vips_object_set(VIPS_OBJECT(op), "a", opts->a, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_subsample(VipsImage * input, int xfac, int yfac, VipsImage ** out_out, GenSubsampleOpts *opts) { - VipsOperation *op = vips_operation_new("subsample"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "input", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xfac", xfac, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yfac", yfac, NULL)) goto error; - - if (opts) { - if (opts->has_point) { - vips_object_set(VIPS_OBJECT(op), "point", (gboolean)opts->point, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_subtract(VipsImage * left, VipsImage * right, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("subtract"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "left", left, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "right", right, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_sum(VipsImage **input, int input_n, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("sum"); - if (!op) return -1; - - { - VipsArrayImage *arr = vips_array_image_new(input, input_n); - int ret = vips_object_set(VIPS_OBJECT(op), "in", arr, NULL); - vips_area_unref(VIPS_AREA(arr)); - if (ret) goto error; - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_tilecache(VipsImage * input, VipsImage ** out_out, GenTilecacheOpts *opts) { - VipsOperation *op = vips_operation_new("tilecache"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_tileWidth) { - vips_object_set(VIPS_OBJECT(op), "tile-width", opts->tileWidth, NULL); - } - if (opts->has_tileHeight) { - vips_object_set(VIPS_OBJECT(op), "tile-height", opts->tileHeight, NULL); - } - if (opts->has_maxTiles) { - vips_object_set(VIPS_OBJECT(op), "max-tiles", opts->maxTiles, NULL); - } - if (opts->has_access) { - vips_object_set(VIPS_OBJECT(op), "access", (int)opts->access, NULL); - } - if (opts->has_threaded) { - vips_object_set(VIPS_OBJECT(op), "threaded", (gboolean)opts->threaded, NULL); - } - if (opts->has_persistent) { - vips_object_set(VIPS_OBJECT(op), "persistent", (gboolean)opts->persistent, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_tonelut(VipsImage ** out_out, GenTonelutOpts *opts) { - VipsOperation *op = vips_operation_new("tonelut"); - if (!op) return -1; - - - if (opts) { - if (opts->has_inMax) { - vips_object_set(VIPS_OBJECT(op), "in-max", opts->inMax, NULL); - } - if (opts->has_outMax) { - vips_object_set(VIPS_OBJECT(op), "out-max", opts->outMax, NULL); - } - if (opts->has_Lb) { - vips_object_set(VIPS_OBJECT(op), "Lb", opts->Lb, NULL); - } - if (opts->has_Lw) { - vips_object_set(VIPS_OBJECT(op), "Lw", opts->Lw, NULL); - } - if (opts->has_Ps) { - vips_object_set(VIPS_OBJECT(op), "Ps", opts->Ps, NULL); - } - if (opts->has_Pm) { - vips_object_set(VIPS_OBJECT(op), "Pm", opts->Pm, NULL); - } - if (opts->has_Ph) { - vips_object_set(VIPS_OBJECT(op), "Ph", opts->Ph, NULL); - } - if (opts->has_S) { - vips_object_set(VIPS_OBJECT(op), "S", opts->S, NULL); - } - if (opts->has_M) { - vips_object_set(VIPS_OBJECT(op), "M", opts->M, NULL); - } - if (opts->has_H) { - vips_object_set(VIPS_OBJECT(op), "H", opts->H, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_transpose3d(VipsImage * input, VipsImage ** out_out, GenTranspose3dOpts *opts) { - VipsOperation *op = vips_operation_new("transpose3d"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_pageHeight) { - vips_object_set(VIPS_OBJECT(op), "page-height", opts->pageHeight, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_uhdr2scRGB(VipsImage * input, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("uhdr2scRGB"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_unpremultiply(VipsImage * input, VipsImage ** out_out, GenUnpremultiplyOpts *opts) { - VipsOperation *op = vips_operation_new("unpremultiply"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_maxAlpha) { - vips_object_set(VIPS_OBJECT(op), "max-alpha", opts->maxAlpha, NULL); - } - if (opts->has_alphaBand) { - vips_object_set(VIPS_OBJECT(op), "alpha-band", opts->alphaBand, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_worley(int width, int height, VipsImage ** out_out, GenWorleyOpts *opts) { - VipsOperation *op = vips_operation_new("worley"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_cellSize) { - vips_object_set(VIPS_OBJECT(op), "cell-size", opts->cellSize, NULL); - } - if (opts->has_seed) { - vips_object_set(VIPS_OBJECT(op), "seed", opts->seed, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_wrap(VipsImage * input, VipsImage ** out_out, GenWrapOpts *opts) { - VipsOperation *op = vips_operation_new("wrap"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "in", input, NULL)) goto error; - - if (opts) { - if (opts->has_x) { - vips_object_set(VIPS_OBJECT(op), "x", opts->x, NULL); - } - if (opts->has_y) { - vips_object_set(VIPS_OBJECT(op), "y", opts->y, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_xyz(int width, int height, VipsImage ** out_out, GenXyzOpts *opts) { - VipsOperation *op = vips_operation_new("xyz"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_csize) { - vips_object_set(VIPS_OBJECT(op), "csize", opts->csize, NULL); - } - if (opts->has_dsize) { - vips_object_set(VIPS_OBJECT(op), "dsize", opts->dsize, NULL); - } - if (opts->has_esize) { - vips_object_set(VIPS_OBJECT(op), "esize", opts->esize, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_zone(int width, int height, VipsImage ** out_out, GenZoneOpts *opts) { - VipsOperation *op = vips_operation_new("zone"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "width", width, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "height", height, NULL)) goto error; - - if (opts) { - if (opts->has_uchar) { - vips_object_set(VIPS_OBJECT(op), "uchar", (gboolean)opts->uchar, NULL); - } - } - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - -int gen_vips_zoom(VipsImage * input, int xfac, int yfac, VipsImage ** out_out) { - VipsOperation *op = vips_operation_new("zoom"); - if (!op) return -1; - - if (vips_object_set(VIPS_OBJECT(op), "input", input, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "xfac", xfac, NULL)) goto error; - if (vips_object_set(VIPS_OBJECT(op), "yfac", yfac, NULL)) goto error; - - if (vips_cache_operation_buildp(&op)) goto error; - - g_object_get(VIPS_OBJECT(op), "out", out_out, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return 0; - -error: - vips_object_unref_outputs(VIPS_OBJECT(op)); - g_object_unref(op); - return -1; -} - diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/generated.go b/vendor/github.com/davidbyttow/govips/v2/vips/generated.go deleted file mode 100644 index 03237add33..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/generated.go +++ /dev/null @@ -1,5001 +0,0 @@ -// Code generated by vipsgen. DO NOT EDIT. -package vips - -// #include "generated.h" -import "C" - -import ( - "runtime" - "unsafe" -) - -// Ensure imports are used. -var _ = unsafe.Pointer(nil) - -// vipsGenCMC2LCh calls the vips CMC2LCh operation. -// transform LCh to CMC -func vipsGenCMC2LCh(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("CMC2LCh") - - var out_out *C.VipsImage - - ret := C.gen_vips_CMC2LCh(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenCMYK2XYZ calls the vips CMYK2XYZ operation. -// transform CMYK to XYZ -func vipsGenCMYK2XYZ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("CMYK2XYZ") - - var out_out *C.VipsImage - - ret := C.gen_vips_CMYK2XYZ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHSV2sRGB calls the vips HSV2sRGB operation. -// transform HSV to sRGB -func vipsGenHSV2sRGB(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("HSV2sRGB") - - var out_out *C.VipsImage - - ret := C.gen_vips_HSV2sRGB(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLCh2CMC calls the vips LCh2CMC operation. -// transform LCh to CMC -func vipsGenLCh2CMC(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LCh2CMC") - - var out_out *C.VipsImage - - ret := C.gen_vips_LCh2CMC(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLCh2Lab calls the vips LCh2Lab operation. -// transform LCh to Lab -func vipsGenLCh2Lab(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LCh2Lab") - - var out_out *C.VipsImage - - ret := C.gen_vips_LCh2Lab(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLab2LCh calls the vips Lab2LCh operation. -// transform Lab to LCh -func vipsGenLab2LCh(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Lab2LCh") - - var out_out *C.VipsImage - - ret := C.gen_vips_Lab2LCh(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLab2LabQ calls the vips Lab2LabQ operation. -// transform float Lab to LabQ coding -func vipsGenLab2LabQ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Lab2LabQ") - - var out_out *C.VipsImage - - ret := C.gen_vips_Lab2LabQ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLab2LabS calls the vips Lab2LabS operation. -// transform float Lab to signed short -func vipsGenLab2LabS(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Lab2LabS") - - var out_out *C.VipsImage - - ret := C.gen_vips_Lab2LabS(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// Lab2XYZOptions are optional parameters for Lab2XYZ. -type Lab2XYZOptions struct { - Temp []float64 -} - -// vipsGenLab2XYZ calls the vips Lab2XYZ operation. -// transform CIELAB to XYZ -func vipsGenLab2XYZ(input *C.VipsImage, opts *Lab2XYZOptions) (*C.VipsImage, error) { - incOpCounter("Lab2XYZ") - - var out_out *C.VipsImage - - var cOpts C.GenLab2XYZOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Temp != nil { - cOpts.has_temp = 1 - pinner.Pin(&opts.Temp[0]) - cOpts.temp = (*C.double)(unsafe.Pointer(&opts.Temp[0])) - cOpts.temp_n = C.int(len(opts.Temp)) - } - } - - ret := C.gen_vips_Lab2XYZ(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabQ2Lab calls the vips LabQ2Lab operation. -// unpack a LabQ image to float Lab -func vipsGenLabQ2Lab(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LabQ2Lab") - - var out_out *C.VipsImage - - ret := C.gen_vips_LabQ2Lab(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabQ2LabS calls the vips LabQ2LabS operation. -// unpack a LabQ image to short Lab -func vipsGenLabQ2LabS(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LabQ2LabS") - - var out_out *C.VipsImage - - ret := C.gen_vips_LabQ2LabS(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabQ2sRGB calls the vips LabQ2sRGB operation. -// convert a LabQ image to sRGB -func vipsGenLabQ2sRGB(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LabQ2sRGB") - - var out_out *C.VipsImage - - ret := C.gen_vips_LabQ2sRGB(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabS2Lab calls the vips LabS2Lab operation. -// transform signed short Lab to float -func vipsGenLabS2Lab(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LabS2Lab") - - var out_out *C.VipsImage - - ret := C.gen_vips_LabS2Lab(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabS2LabQ calls the vips LabS2LabQ operation. -// transform short Lab to LabQ coding -func vipsGenLabS2LabQ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("LabS2LabQ") - - var out_out *C.VipsImage - - ret := C.gen_vips_LabS2LabQ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenOklab2Oklch calls the vips Oklab2Oklch operation. -// transform Oklab to Oklch -func vipsGenOklab2Oklch(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Oklab2Oklch") - - var out_out *C.VipsImage - - ret := C.gen_vips_Oklab2Oklch(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenOklab2XYZ calls the vips Oklab2XYZ operation. -// transform Oklab to XYZ -func vipsGenOklab2XYZ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Oklab2XYZ") - - var out_out *C.VipsImage - - ret := C.gen_vips_Oklab2XYZ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenOklch2Oklab calls the vips Oklch2Oklab operation. -// transform Oklch to Oklab -func vipsGenOklch2Oklab(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Oklch2Oklab") - - var out_out *C.VipsImage - - ret := C.gen_vips_Oklch2Oklab(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenXYZ2CMYK calls the vips XYZ2CMYK operation. -// transform XYZ to CMYK -func vipsGenXYZ2CMYK(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("XYZ2CMYK") - - var out_out *C.VipsImage - - ret := C.gen_vips_XYZ2CMYK(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// XYZ2LabOptions are optional parameters for XYZ2Lab. -type XYZ2LabOptions struct { - Temp []float64 -} - -// vipsGenXYZ2Lab calls the vips XYZ2Lab operation. -// transform XYZ to Lab -func vipsGenXYZ2Lab(input *C.VipsImage, opts *XYZ2LabOptions) (*C.VipsImage, error) { - incOpCounter("XYZ2Lab") - - var out_out *C.VipsImage - - var cOpts C.GenXYZ2LabOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Temp != nil { - cOpts.has_temp = 1 - pinner.Pin(&opts.Temp[0]) - cOpts.temp = (*C.double)(unsafe.Pointer(&opts.Temp[0])) - cOpts.temp_n = C.int(len(opts.Temp)) - } - } - - ret := C.gen_vips_XYZ2Lab(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenXYZ2Oklab calls the vips XYZ2Oklab operation. -// transform XYZ to Oklab -func vipsGenXYZ2Oklab(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("XYZ2Oklab") - - var out_out *C.VipsImage - - ret := C.gen_vips_XYZ2Oklab(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenXYZ2Yxy calls the vips XYZ2Yxy operation. -// transform XYZ to Yxy -func vipsGenXYZ2Yxy(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("XYZ2Yxy") - - var out_out *C.VipsImage - - ret := C.gen_vips_XYZ2Yxy(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenXYZ2scRGB calls the vips XYZ2scRGB operation. -// transform XYZ to scRGB -func vipsGenXYZ2scRGB(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("XYZ2scRGB") - - var out_out *C.VipsImage - - ret := C.gen_vips_XYZ2scRGB(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenYxy2XYZ calls the vips Yxy2XYZ operation. -// transform Yxy to XYZ -func vipsGenYxy2XYZ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("Yxy2XYZ") - - var out_out *C.VipsImage - - ret := C.gen_vips_Yxy2XYZ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenAbs calls the vips abs operation. -// absolute value of an image -func vipsGenAbs(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("abs") - - var out_out *C.VipsImage - - ret := C.gen_vips_abs(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenAdd calls the vips add operation. -// add two images -func vipsGenAdd(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("add") - - var out_out *C.VipsImage - - ret := C.gen_vips_add(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// AffineOptions are optional parameters for affine. -type AffineOptions struct { - Interpolate *C.VipsInterpolate - Oarea []int - Odx *float64 - Ody *float64 - Idx *float64 - Idy *float64 - Background []float64 - Premultiplied *bool - Extend *ExtendStrategy -} - -// vipsGenAffine calls the vips affine operation. -// affine transform of an image -func vipsGenAffine(input *C.VipsImage, matrix []float64, opts *AffineOptions) (*C.VipsImage, error) { - incOpCounter("affine") - - var out_out *C.VipsImage - - var cOpts C.GenAffineOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - if opts.Oarea != nil { - cOpts.has_oarea = 1 - pinner.Pin(&opts.Oarea[0]) - cOpts.oarea = (*C.int)(unsafe.Pointer(&opts.Oarea[0])) - cOpts.oarea_n = C.int(len(opts.Oarea)) - } - if opts.Odx != nil { - cOpts.has_odx = 1 - cOpts.odx = C.double(*opts.Odx) - } - if opts.Ody != nil { - cOpts.has_ody = 1 - cOpts.ody = C.double(*opts.Ody) - } - if opts.Idx != nil { - cOpts.has_idx = 1 - cOpts.idx = C.double(*opts.Idx) - } - if opts.Idy != nil { - cOpts.has_idy = 1 - cOpts.idy = C.double(*opts.Idy) - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Premultiplied != nil { - cOpts.has_premultiplied = 1 - cOpts.premultiplied = C.int(boolToInt(*opts.Premultiplied)) - } - if opts.Extend != nil { - cOpts.has_extend = 1 - cOpts.extend = C.VipsExtend(*opts.Extend) - } - } - - ret := C.gen_vips_affine(input, (*C.double)(unsafe.Pointer(&matrix[0])), C.int(len(matrix)), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ArrayjoinOptions are optional parameters for arrayjoin. -type ArrayjoinOptions struct { - Across *int - Shim *int - Background []float64 - Halign *Align - Valign *Align - Hspacing *int - Vspacing *int -} - -// vipsGenArrayjoin calls the vips arrayjoin operation. -// join an array of images -func vipsGenArrayjoin(input []*C.VipsImage, opts *ArrayjoinOptions) (*C.VipsImage, error) { - incOpCounter("arrayjoin") - - var out_out *C.VipsImage - - var cOpts C.GenArrayjoinOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Across != nil { - cOpts.has_across = 1 - cOpts.across = C.int(*opts.Across) - } - if opts.Shim != nil { - cOpts.has_shim = 1 - cOpts.shim = C.int(*opts.Shim) - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Halign != nil { - cOpts.has_halign = 1 - cOpts.halign = C.VipsAlign(*opts.Halign) - } - if opts.Valign != nil { - cOpts.has_valign = 1 - cOpts.valign = C.VipsAlign(*opts.Valign) - } - if opts.Hspacing != nil { - cOpts.has_hspacing = 1 - cOpts.hspacing = C.int(*opts.Hspacing) - } - if opts.Vspacing != nil { - cOpts.has_vspacing = 1 - cOpts.vspacing = C.int(*opts.Vspacing) - } - } - - ret := C.gen_vips_arrayjoin((**C.VipsImage)(unsafe.Pointer(&input[0])), C.int(len(input)), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenAutorot calls the vips autorot operation. -// autorotate image by exif tag -func vipsGenAutorot(input *C.VipsImage) (*C.VipsImage, Angle, bool, error) { - incOpCounter("autorot") - - var out_out *C.VipsImage - var out_angle C.int - var out_flip C.int - - ret := C.gen_vips_autorot(input, &out_out, &out_angle, &out_flip) - if ret != 0 { - return nil, 0, false, handleImageError(out_out) - } - - return out_out, Angle(out_angle), out_flip != 0, nil -} - -// vipsGenAvg calls the vips avg operation. -// find image average -func vipsGenAvg(input *C.VipsImage) (float64, error) { - incOpCounter("avg") - - var out_out C.double - - ret := C.gen_vips_avg(input, &out_out) - if ret != 0 { - return 0, handleVipsError() - } - - return float64(out_out), nil -} - -// vipsGenBandbool calls the vips bandbool operation. -// boolean operation across image bands -func vipsGenBandbool(input *C.VipsImage, boolean OperationBoolean) (*C.VipsImage, error) { - incOpCounter("bandbool") - - var out_out *C.VipsImage - - ret := C.gen_vips_bandbool(input, C.VipsOperationBoolean(boolean), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// BandfoldOptions are optional parameters for bandfold. -type BandfoldOptions struct { - Factor *int -} - -// vipsGenBandfold calls the vips bandfold operation. -// fold up x axis into bands -func vipsGenBandfold(input *C.VipsImage, opts *BandfoldOptions) (*C.VipsImage, error) { - incOpCounter("bandfold") - - var out_out *C.VipsImage - - var cOpts C.GenBandfoldOpts - if opts != nil { - if opts.Factor != nil { - cOpts.has_factor = 1 - cOpts.factor = C.int(*opts.Factor) - } - } - - ret := C.gen_vips_bandfold(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBandjoin calls the vips bandjoin operation. -// bandwise join a set of images -func vipsGenBandjoin(input []*C.VipsImage) (*C.VipsImage, error) { - incOpCounter("bandjoin") - - var out_out *C.VipsImage - - ret := C.gen_vips_bandjoin((**C.VipsImage)(unsafe.Pointer(&input[0])), C.int(len(input)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBandjoinConst calls the vips bandjoin_const operation. -// append a constant band to an image -func vipsGenBandjoinConst(input *C.VipsImage, c []float64) (*C.VipsImage, error) { - incOpCounter("bandjoin_const") - - var out_out *C.VipsImage - - ret := C.gen_vips_bandjoin_const(input, (*C.double)(unsafe.Pointer(&c[0])), C.int(len(c)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBandmean calls the vips bandmean operation. -// band-wise average -func vipsGenBandmean(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("bandmean") - - var out_out *C.VipsImage - - ret := C.gen_vips_bandmean(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// BandrankOptions are optional parameters for bandrank. -type BandrankOptions struct { - Index *int -} - -// vipsGenBandrank calls the vips bandrank operation. -// band-wise rank of a set of images -func vipsGenBandrank(input []*C.VipsImage, opts *BandrankOptions) (*C.VipsImage, error) { - incOpCounter("bandrank") - - var out_out *C.VipsImage - - var cOpts C.GenBandrankOpts - if opts != nil { - if opts.Index != nil { - cOpts.has_index = 1 - cOpts.index = C.int(*opts.Index) - } - } - - ret := C.gen_vips_bandrank((**C.VipsImage)(unsafe.Pointer(&input[0])), C.int(len(input)), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// BandunfoldOptions are optional parameters for bandunfold. -type BandunfoldOptions struct { - Factor *int -} - -// vipsGenBandunfold calls the vips bandunfold operation. -// unfold image bands into x axis -func vipsGenBandunfold(input *C.VipsImage, opts *BandunfoldOptions) (*C.VipsImage, error) { - incOpCounter("bandunfold") - - var out_out *C.VipsImage - - var cOpts C.GenBandunfoldOpts - if opts != nil { - if opts.Factor != nil { - cOpts.has_factor = 1 - cOpts.factor = C.int(*opts.Factor) - } - } - - ret := C.gen_vips_bandunfold(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// BlackOptions are optional parameters for black. -type BlackOptions struct { - Bands *int -} - -// vipsGenBlack calls the vips black operation. -// make a black image -func vipsGenBlack(width int, height int, opts *BlackOptions) (*C.VipsImage, error) { - incOpCounter("black") - - var out_out *C.VipsImage - - var cOpts C.GenBlackOpts - if opts != nil { - if opts.Bands != nil { - cOpts.has_bands = 1 - cOpts.bands = C.int(*opts.Bands) - } - } - - ret := C.gen_vips_black(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBoolean calls the vips boolean operation. -// boolean operation on two images -func vipsGenBoolean(left *C.VipsImage, right *C.VipsImage, boolean OperationBoolean) (*C.VipsImage, error) { - incOpCounter("boolean") - - var out_out *C.VipsImage - - ret := C.gen_vips_boolean(left, right, C.VipsOperationBoolean(boolean), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBooleanConst calls the vips boolean_const operation. -// boolean operations against a constant -func vipsGenBooleanConst(input *C.VipsImage, boolean OperationBoolean, c []float64) (*C.VipsImage, error) { - incOpCounter("boolean_const") - - var out_out *C.VipsImage - - ret := C.gen_vips_boolean_const(input, C.VipsOperationBoolean(boolean), (*C.double)(unsafe.Pointer(&c[0])), C.int(len(c)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenBuildlut calls the vips buildlut operation. -// build a look-up table -func vipsGenBuildlut(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("buildlut") - - var out_out *C.VipsImage - - ret := C.gen_vips_buildlut(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenByteswap calls the vips byteswap operation. -// byteswap an image -func vipsGenByteswap(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("byteswap") - - var out_out *C.VipsImage - - ret := C.gen_vips_byteswap(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// CacheOptions are optional parameters for cache. -type CacheOptions struct { - MaxTiles *int - TileHeight *int - TileWidth *int -} - -// vipsGenCache calls the vips cache operation. -// cache an image -func vipsGenCache(input *C.VipsImage, opts *CacheOptions) (*C.VipsImage, error) { - incOpCounter("cache") - - var out_out *C.VipsImage - - var cOpts C.GenCacheOpts - if opts != nil { - if opts.MaxTiles != nil { - cOpts.has_maxTiles = 1 - cOpts.maxTiles = C.int(*opts.MaxTiles) - } - if opts.TileHeight != nil { - cOpts.has_tileHeight = 1 - cOpts.tileHeight = C.int(*opts.TileHeight) - } - if opts.TileWidth != nil { - cOpts.has_tileWidth = 1 - cOpts.tileWidth = C.int(*opts.TileWidth) - } - } - - ret := C.gen_vips_cache(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// CannyOptions are optional parameters for canny. -type CannyOptions struct { - Sigma *float64 - Precision *Precision -} - -// vipsGenCanny calls the vips canny operation. -// Canny edge detector -func vipsGenCanny(input *C.VipsImage, opts *CannyOptions) (*C.VipsImage, error) { - incOpCounter("canny") - - var out_out *C.VipsImage - - var cOpts C.GenCannyOpts - if opts != nil { - if opts.Sigma != nil { - cOpts.has_sigma = 1 - cOpts.sigma = C.double(*opts.Sigma) - } - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - } - - ret := C.gen_vips_canny(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// CastOptions are optional parameters for cast. -type CastOptions struct { - Shift *bool -} - -// vipsGenCast calls the vips cast operation. -// cast an image -func vipsGenCast(input *C.VipsImage, format BandFormat, opts *CastOptions) (*C.VipsImage, error) { - incOpCounter("cast") - - var out_out *C.VipsImage - - var cOpts C.GenCastOpts - if opts != nil { - if opts.Shift != nil { - cOpts.has_shift = 1 - cOpts.shift = C.int(boolToInt(*opts.Shift)) - } - } - - ret := C.gen_vips_cast(input, C.VipsBandFormat(format), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ClampOptions are optional parameters for clamp. -type ClampOptions struct { - Min *float64 - Max *float64 -} - -// vipsGenClamp calls the vips clamp operation. -// clamp values of an image -func vipsGenClamp(input *C.VipsImage, opts *ClampOptions) (*C.VipsImage, error) { - incOpCounter("clamp") - - var out_out *C.VipsImage - - var cOpts C.GenClampOpts - if opts != nil { - if opts.Min != nil { - cOpts.has_min = 1 - cOpts.min = C.double(*opts.Min) - } - if opts.Max != nil { - cOpts.has_max = 1 - cOpts.max = C.double(*opts.Max) - } - } - - ret := C.gen_vips_clamp(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// CompassOptions are optional parameters for compass. -type CompassOptions struct { - Times *int - Angle *Angle45 - Combine *Combine - Precision *Precision - Layers *int - Cluster *int -} - -// vipsGenCompass calls the vips compass operation. -// convolve with rotating mask -func vipsGenCompass(input *C.VipsImage, mask *C.VipsImage, opts *CompassOptions) (*C.VipsImage, error) { - incOpCounter("compass") - - var out_out *C.VipsImage - - var cOpts C.GenCompassOpts - if opts != nil { - if opts.Times != nil { - cOpts.has_times = 1 - cOpts.times = C.int(*opts.Times) - } - if opts.Angle != nil { - cOpts.has_angle = 1 - cOpts.angle = C.VipsAngle45(*opts.Angle) - } - if opts.Combine != nil { - cOpts.has_combine = 1 - cOpts.combine = C.VipsCombine(*opts.Combine) - } - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - if opts.Layers != nil { - cOpts.has_layers = 1 - cOpts.layers = C.int(*opts.Layers) - } - if opts.Cluster != nil { - cOpts.has_cluster = 1 - cOpts.cluster = C.int(*opts.Cluster) - } - } - - ret := C.gen_vips_compass(input, mask, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenComplex calls the vips complex operation. -// perform a complex operation on an image -func vipsGenComplex(input *C.VipsImage, cmplx OperationComplex) (*C.VipsImage, error) { - incOpCounter("complex") - - var out_out *C.VipsImage - - ret := C.gen_vips_complex(input, C.VipsOperationComplex(cmplx), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenComplex2 calls the vips complex2 operation. -// complex binary operations on two images -func vipsGenComplex2(left *C.VipsImage, right *C.VipsImage, cmplx OperationComplex2) (*C.VipsImage, error) { - incOpCounter("complex2") - - var out_out *C.VipsImage - - ret := C.gen_vips_complex2(left, right, C.VipsOperationComplex2(cmplx), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenComplexform calls the vips complexform operation. -// form a complex image from two real images -func vipsGenComplexform(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("complexform") - - var out_out *C.VipsImage - - ret := C.gen_vips_complexform(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenComplexget calls the vips complexget operation. -// get a component from a complex image -func vipsGenComplexget(input *C.VipsImage, get OperationComplexget) (*C.VipsImage, error) { - incOpCounter("complexget") - - var out_out *C.VipsImage - - ret := C.gen_vips_complexget(input, C.VipsOperationComplexget(get), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// Composite2Options are optional parameters for composite2. -type Composite2Options struct { - X *int - Y *int - CompositingSpace *Interpretation - Premultiplied *bool -} - -// vipsGenComposite2 calls the vips composite2 operation. -// blend a pair of images with a blend mode -func vipsGenComposite2(base *C.VipsImage, overlay *C.VipsImage, mode BlendMode, opts *Composite2Options) (*C.VipsImage, error) { - incOpCounter("composite2") - - var out_out *C.VipsImage - - var cOpts C.GenComposite2Opts - if opts != nil { - if opts.X != nil { - cOpts.has_x = 1 - cOpts.x = C.int(*opts.X) - } - if opts.Y != nil { - cOpts.has_y = 1 - cOpts.y = C.int(*opts.Y) - } - if opts.CompositingSpace != nil { - cOpts.has_compositingSpace = 1 - cOpts.compositingSpace = C.VipsInterpretation(*opts.CompositingSpace) - } - if opts.Premultiplied != nil { - cOpts.has_premultiplied = 1 - cOpts.premultiplied = C.int(boolToInt(*opts.Premultiplied)) - } - } - - ret := C.gen_vips_composite2(base, overlay, C.VipsBlendMode(mode), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ConvOptions are optional parameters for conv. -type ConvOptions struct { - Precision *Precision - Layers *int - Cluster *int -} - -// vipsGenConv calls the vips conv operation. -// convolution operation -func vipsGenConv(input *C.VipsImage, mask *C.VipsImage, opts *ConvOptions) (*C.VipsImage, error) { - incOpCounter("conv") - - var out_out *C.VipsImage - - var cOpts C.GenConvOpts - if opts != nil { - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - if opts.Layers != nil { - cOpts.has_layers = 1 - cOpts.layers = C.int(*opts.Layers) - } - if opts.Cluster != nil { - cOpts.has_cluster = 1 - cOpts.cluster = C.int(*opts.Cluster) - } - } - - ret := C.gen_vips_conv(input, mask, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ConvaOptions are optional parameters for conva. -type ConvaOptions struct { - Layers *int - Cluster *int -} - -// vipsGenConva calls the vips conva operation. -// approximate integer convolution -func vipsGenConva(input *C.VipsImage, mask *C.VipsImage, opts *ConvaOptions) (*C.VipsImage, error) { - incOpCounter("conva") - - var out_out *C.VipsImage - - var cOpts C.GenConvaOpts - if opts != nil { - if opts.Layers != nil { - cOpts.has_layers = 1 - cOpts.layers = C.int(*opts.Layers) - } - if opts.Cluster != nil { - cOpts.has_cluster = 1 - cOpts.cluster = C.int(*opts.Cluster) - } - } - - ret := C.gen_vips_conva(input, mask, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ConvasepOptions are optional parameters for convasep. -type ConvasepOptions struct { - Layers *int -} - -// vipsGenConvasep calls the vips convasep operation. -// approximate separable integer convolution -func vipsGenConvasep(input *C.VipsImage, mask *C.VipsImage, opts *ConvasepOptions) (*C.VipsImage, error) { - incOpCounter("convasep") - - var out_out *C.VipsImage - - var cOpts C.GenConvasepOpts - if opts != nil { - if opts.Layers != nil { - cOpts.has_layers = 1 - cOpts.layers = C.int(*opts.Layers) - } - } - - ret := C.gen_vips_convasep(input, mask, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenConvf calls the vips convf operation. -// float convolution operation -func vipsGenConvf(input *C.VipsImage, mask *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("convf") - - var out_out *C.VipsImage - - ret := C.gen_vips_convf(input, mask, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenConvi calls the vips convi operation. -// int convolution operation -func vipsGenConvi(input *C.VipsImage, mask *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("convi") - - var out_out *C.VipsImage - - ret := C.gen_vips_convi(input, mask, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ConvsepOptions are optional parameters for convsep. -type ConvsepOptions struct { - Precision *Precision - Layers *int - Cluster *int -} - -// vipsGenConvsep calls the vips convsep operation. -// separable convolution operation -func vipsGenConvsep(input *C.VipsImage, mask *C.VipsImage, opts *ConvsepOptions) (*C.VipsImage, error) { - incOpCounter("convsep") - - var out_out *C.VipsImage - - var cOpts C.GenConvsepOpts - if opts != nil { - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - if opts.Layers != nil { - cOpts.has_layers = 1 - cOpts.layers = C.int(*opts.Layers) - } - if opts.Cluster != nil { - cOpts.has_cluster = 1 - cOpts.cluster = C.int(*opts.Cluster) - } - } - - ret := C.gen_vips_convsep(input, mask, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// CopyOptions are optional parameters for copy. -type CopyOptions struct { - Width *int - Height *int - Bands *int - Format *BandFormat - Coding *Coding - Interpretation *Interpretation - Xres *float64 - Yres *float64 - Xoffset *int - Yoffset *int -} - -// vipsGenCopy calls the vips copy operation. -// copy an image -func vipsGenCopy(input *C.VipsImage, opts *CopyOptions) (*C.VipsImage, error) { - incOpCounter("copy") - - var out_out *C.VipsImage - - var cOpts C.GenCopyOpts - if opts != nil { - if opts.Width != nil { - cOpts.has_width = 1 - cOpts.width = C.int(*opts.Width) - } - if opts.Height != nil { - cOpts.has_height = 1 - cOpts.height = C.int(*opts.Height) - } - if opts.Bands != nil { - cOpts.has_bands = 1 - cOpts.bands = C.int(*opts.Bands) - } - if opts.Format != nil { - cOpts.has_format = 1 - cOpts.format = C.VipsBandFormat(*opts.Format) - } - if opts.Coding != nil { - cOpts.has_coding = 1 - cOpts.coding = C.VipsCoding(*opts.Coding) - } - if opts.Interpretation != nil { - cOpts.has_interpretation = 1 - cOpts.interpretation = C.VipsInterpretation(*opts.Interpretation) - } - if opts.Xres != nil { - cOpts.has_xres = 1 - cOpts.xres = C.double(*opts.Xres) - } - if opts.Yres != nil { - cOpts.has_yres = 1 - cOpts.yres = C.double(*opts.Yres) - } - if opts.Xoffset != nil { - cOpts.has_xoffset = 1 - cOpts.xoffset = C.int(*opts.Xoffset) - } - if opts.Yoffset != nil { - cOpts.has_yoffset = 1 - cOpts.yoffset = C.int(*opts.Yoffset) - } - } - - ret := C.gen_vips_copy(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenCountlines calls the vips countlines operation. -// count lines in an image -func vipsGenCountlines(input *C.VipsImage, direction Direction) (float64, error) { - incOpCounter("countlines") - - var out_nolines C.double - - ret := C.gen_vips_countlines(input, C.VipsDirection(direction), &out_nolines) - if ret != 0 { - return 0, handleVipsError() - } - - return float64(out_nolines), nil -} - -// vipsGenDE00 calls the vips dE00 operation. -// calculate dE00 -func vipsGenDE00(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("dE00") - - var out_out *C.VipsImage - - ret := C.gen_vips_dE00(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenDE76 calls the vips dE76 operation. -// calculate dE76 -func vipsGenDE76(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("dE76") - - var out_out *C.VipsImage - - ret := C.gen_vips_dE76(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenDECMC calls the vips dECMC operation. -// calculate dECMC -func vipsGenDECMC(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("dECMC") - - var out_out *C.VipsImage - - ret := C.gen_vips_dECMC(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenDeviate calls the vips deviate operation. -// find image standard deviation -func vipsGenDeviate(input *C.VipsImage) (float64, error) { - incOpCounter("deviate") - - var out_out C.double - - ret := C.gen_vips_deviate(input, &out_out) - if ret != 0 { - return 0, handleVipsError() - } - - return float64(out_out), nil -} - -// vipsGenDivide calls the vips divide operation. -// divide two images -func vipsGenDivide(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("divide") - - var out_out *C.VipsImage - - ret := C.gen_vips_divide(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenExtractArea calls the vips extract_area operation. -// extract an area from an image -func vipsGenExtractArea(input *C.VipsImage, left int, top int, width int, height int) (*C.VipsImage, error) { - incOpCounter("extract_area") - - var out_out *C.VipsImage - - ret := C.gen_vips_extract_area(input, C.int(left), C.int(top), C.int(width), C.int(height), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ExtractBandOptions are optional parameters for extract_band. -type ExtractBandOptions struct { - N *int -} - -// vipsGenExtractBand calls the vips extract_band operation. -// extract band from an image -func vipsGenExtractBand(input *C.VipsImage, band int, opts *ExtractBandOptions) (*C.VipsImage, error) { - incOpCounter("extract_band") - - var out_out *C.VipsImage - - var cOpts C.GenExtractBandOpts - if opts != nil { - if opts.N != nil { - cOpts.has_n = 1 - cOpts.n = C.int(*opts.N) - } - } - - ret := C.gen_vips_extract_band(input, C.int(band), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// EyeOptions are optional parameters for eye. -type EyeOptions struct { - Uchar *bool - Factor *float64 -} - -// vipsGenEye calls the vips eye operation. -// make an image showing the eye's spatial response -func vipsGenEye(width int, height int, opts *EyeOptions) (*C.VipsImage, error) { - incOpCounter("eye") - - var out_out *C.VipsImage - - var cOpts C.GenEyeOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Factor != nil { - cOpts.has_factor = 1 - cOpts.factor = C.double(*opts.Factor) - } - } - - ret := C.gen_vips_eye(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFalsecolour calls the vips falsecolour operation. -// false-color an image -func vipsGenFalsecolour(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("falsecolour") - - var out_out *C.VipsImage - - ret := C.gen_vips_falsecolour(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFastcor calls the vips fastcor operation. -// fast correlation -func vipsGenFastcor(input *C.VipsImage, ref *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("fastcor") - - var out_out *C.VipsImage - - ret := C.gen_vips_fastcor(input, ref, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFillNearest calls the vips fill_nearest operation. -// fill image zeros with nearest non-zero pixel -func vipsGenFillNearest(input *C.VipsImage) (*C.VipsImage, *C.VipsImage, error) { - incOpCounter("fill_nearest") - - var out_out *C.VipsImage - var out_distance *C.VipsImage - - ret := C.gen_vips_fill_nearest(input, &out_out, &out_distance) - if ret != 0 { - return nil, nil, handleImageError(out_out) - } - - return out_out, out_distance, nil -} - -// FlattenOptions are optional parameters for flatten. -type FlattenOptions struct { - Background []float64 - MaxAlpha *float64 -} - -// vipsGenFlatten calls the vips flatten operation. -// flatten alpha out of an image -func vipsGenFlatten(input *C.VipsImage, opts *FlattenOptions) (*C.VipsImage, error) { - incOpCounter("flatten") - - var out_out *C.VipsImage - - var cOpts C.GenFlattenOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.MaxAlpha != nil { - cOpts.has_maxAlpha = 1 - cOpts.maxAlpha = C.double(*opts.MaxAlpha) - } - } - - ret := C.gen_vips_flatten(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFlip calls the vips flip operation. -// flip an image -func vipsGenFlip(input *C.VipsImage, direction Direction) (*C.VipsImage, error) { - incOpCounter("flip") - - var out_out *C.VipsImage - - ret := C.gen_vips_flip(input, C.VipsDirection(direction), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFloat2rad calls the vips float2rad operation. -// transform float RGB to Radiance coding -func vipsGenFloat2rad(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("float2rad") - - var out_out *C.VipsImage - - ret := C.gen_vips_float2rad(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFractsurf calls the vips fractsurf operation. -// make a fractal surface -func vipsGenFractsurf(width int, height int, fractalDimension float64) (*C.VipsImage, error) { - incOpCounter("fractsurf") - - var out_out *C.VipsImage - - ret := C.gen_vips_fractsurf(C.int(width), C.int(height), C.double(fractalDimension), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFreqmult calls the vips freqmult operation. -// frequency-domain filtering -func vipsGenFreqmult(input *C.VipsImage, mask *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("freqmult") - - var out_out *C.VipsImage - - ret := C.gen_vips_freqmult(input, mask, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenFwfft calls the vips fwfft operation. -// forward FFT -func vipsGenFwfft(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("fwfft") - - var out_out *C.VipsImage - - ret := C.gen_vips_fwfft(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GammaOptions are optional parameters for gamma. -type GammaOptions struct { - Exponent *float64 -} - -// vipsGenGamma calls the vips gamma operation. -// gamma an image -func vipsGenGamma(input *C.VipsImage, opts *GammaOptions) (*C.VipsImage, error) { - incOpCounter("gamma") - - var out_out *C.VipsImage - - var cOpts C.GenGammaOpts - if opts != nil { - if opts.Exponent != nil { - cOpts.has_exponent = 1 - cOpts.exponent = C.double(*opts.Exponent) - } - } - - ret := C.gen_vips_gamma(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GaussblurOptions are optional parameters for gaussblur. -type GaussblurOptions struct { - MinAmpl *float64 - Precision *Precision -} - -// vipsGenGaussblur calls the vips gaussblur operation. -// gaussian blur -func vipsGenGaussblur(input *C.VipsImage, sigma float64, opts *GaussblurOptions) (*C.VipsImage, error) { - incOpCounter("gaussblur") - - var out_out *C.VipsImage - - var cOpts C.GenGaussblurOpts - if opts != nil { - if opts.MinAmpl != nil { - cOpts.has_minAmpl = 1 - cOpts.minAmpl = C.double(*opts.MinAmpl) - } - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - } - - ret := C.gen_vips_gaussblur(input, C.double(sigma), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GaussmatOptions are optional parameters for gaussmat. -type GaussmatOptions struct { - Separable *bool - Precision *Precision -} - -// vipsGenGaussmat calls the vips gaussmat operation. -// make a gaussian image -func vipsGenGaussmat(sigma float64, minAmpl float64, opts *GaussmatOptions) (*C.VipsImage, error) { - incOpCounter("gaussmat") - - var out_out *C.VipsImage - - var cOpts C.GenGaussmatOpts - if opts != nil { - if opts.Separable != nil { - cOpts.has_separable = 1 - cOpts.separable = C.int(boolToInt(*opts.Separable)) - } - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - } - - ret := C.gen_vips_gaussmat(C.double(sigma), C.double(minAmpl), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GaussnoiseOptions are optional parameters for gaussnoise. -type GaussnoiseOptions struct { - Sigma *float64 - Mean *float64 - Seed *int -} - -// vipsGenGaussnoise calls the vips gaussnoise operation. -// make a gaussnoise image -func vipsGenGaussnoise(width int, height int, opts *GaussnoiseOptions) (*C.VipsImage, error) { - incOpCounter("gaussnoise") - - var out_out *C.VipsImage - - var cOpts C.GenGaussnoiseOpts - if opts != nil { - if opts.Sigma != nil { - cOpts.has_sigma = 1 - cOpts.sigma = C.double(*opts.Sigma) - } - if opts.Mean != nil { - cOpts.has_mean = 1 - cOpts.mean = C.double(*opts.Mean) - } - if opts.Seed != nil { - cOpts.has_seed = 1 - cOpts.seed = C.int(*opts.Seed) - } - } - - ret := C.gen_vips_gaussnoise(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GlobalbalanceOptions are optional parameters for globalbalance. -type GlobalbalanceOptions struct { - Gamma *float64 - IntOutput *bool -} - -// vipsGenGlobalbalance calls the vips globalbalance operation. -// global balance an image mosaic -func vipsGenGlobalbalance(input *C.VipsImage, opts *GlobalbalanceOptions) (*C.VipsImage, error) { - incOpCounter("globalbalance") - - var out_out *C.VipsImage - - var cOpts C.GenGlobalbalanceOpts - if opts != nil { - if opts.Gamma != nil { - cOpts.has_gamma = 1 - cOpts.gamma = C.double(*opts.Gamma) - } - if opts.IntOutput != nil { - cOpts.has_intOutput = 1 - cOpts.intOutput = C.int(boolToInt(*opts.IntOutput)) - } - } - - ret := C.gen_vips_globalbalance(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GravityOptions are optional parameters for gravity. -type GravityOptions struct { - Extend *ExtendStrategy - Background []float64 -} - -// vipsGenGravity calls the vips gravity operation. -// place an image within a larger image with a certain gravity -func vipsGenGravity(input *C.VipsImage, direction Gravity, width int, height int, opts *GravityOptions) (*C.VipsImage, error) { - incOpCounter("gravity") - - var out_out *C.VipsImage - - var cOpts C.GenGravityOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Extend != nil { - cOpts.has_extend = 1 - cOpts.extend = C.VipsExtend(*opts.Extend) - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - } - - ret := C.gen_vips_gravity(input, C.VipsCompassDirection(direction), C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// GreyOptions are optional parameters for grey. -type GreyOptions struct { - Uchar *bool -} - -// vipsGenGrey calls the vips grey operation. -// make a grey ramp image -func vipsGenGrey(width int, height int, opts *GreyOptions) (*C.VipsImage, error) { - incOpCounter("grey") - - var out_out *C.VipsImage - - var cOpts C.GenGreyOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - } - - ret := C.gen_vips_grey(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenGrid calls the vips grid operation. -// grid an image -func vipsGenGrid(input *C.VipsImage, tileHeight int, across int, down int) (*C.VipsImage, error) { - incOpCounter("grid") - - var out_out *C.VipsImage - - ret := C.gen_vips_grid(input, C.int(tileHeight), C.int(across), C.int(down), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistCum calls the vips hist_cum operation. -// form cumulative histogram -func vipsGenHistCum(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("hist_cum") - - var out_out *C.VipsImage - - ret := C.gen_vips_hist_cum(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistEntropy calls the vips hist_entropy operation. -// estimate image entropy -func vipsGenHistEntropy(input *C.VipsImage) (float64, error) { - incOpCounter("hist_entropy") - - var out_out C.double - - ret := C.gen_vips_hist_entropy(input, &out_out) - if ret != 0 { - return 0, handleVipsError() - } - - return float64(out_out), nil -} - -// HistEqualOptions are optional parameters for hist_equal. -type HistEqualOptions struct { - Band *int -} - -// vipsGenHistEqual calls the vips hist_equal operation. -// histogram equalisation -func vipsGenHistEqual(input *C.VipsImage, opts *HistEqualOptions) (*C.VipsImage, error) { - incOpCounter("hist_equal") - - var out_out *C.VipsImage - - var cOpts C.GenHistEqualOpts - if opts != nil { - if opts.Band != nil { - cOpts.has_band = 1 - cOpts.band = C.int(*opts.Band) - } - } - - ret := C.gen_vips_hist_equal(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// HistFindOptions are optional parameters for hist_find. -type HistFindOptions struct { - Band *int -} - -// vipsGenHistFind calls the vips hist_find operation. -// find image histogram -func vipsGenHistFind(input *C.VipsImage, opts *HistFindOptions) (*C.VipsImage, error) { - incOpCounter("hist_find") - - var out_out *C.VipsImage - - var cOpts C.GenHistFindOpts - if opts != nil { - if opts.Band != nil { - cOpts.has_band = 1 - cOpts.band = C.int(*opts.Band) - } - } - - ret := C.gen_vips_hist_find(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// HistFindIndexedOptions are optional parameters for hist_find_indexed. -type HistFindIndexedOptions struct { - Combine *Combine -} - -// vipsGenHistFindIndexed calls the vips hist_find_indexed operation. -// find indexed image histogram -func vipsGenHistFindIndexed(input *C.VipsImage, index *C.VipsImage, opts *HistFindIndexedOptions) (*C.VipsImage, error) { - incOpCounter("hist_find_indexed") - - var out_out *C.VipsImage - - var cOpts C.GenHistFindIndexedOpts - if opts != nil { - if opts.Combine != nil { - cOpts.has_combine = 1 - cOpts.combine = C.VipsCombine(*opts.Combine) - } - } - - ret := C.gen_vips_hist_find_indexed(input, index, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// HistFindNdimOptions are optional parameters for hist_find_ndim. -type HistFindNdimOptions struct { - Bins *int -} - -// vipsGenHistFindNdim calls the vips hist_find_ndim operation. -// find n-dimensional image histogram -func vipsGenHistFindNdim(input *C.VipsImage, opts *HistFindNdimOptions) (*C.VipsImage, error) { - incOpCounter("hist_find_ndim") - - var out_out *C.VipsImage - - var cOpts C.GenHistFindNdimOpts - if opts != nil { - if opts.Bins != nil { - cOpts.has_bins = 1 - cOpts.bins = C.int(*opts.Bins) - } - } - - ret := C.gen_vips_hist_find_ndim(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistIsmonotonic calls the vips hist_ismonotonic operation. -// test for monotonicity -func vipsGenHistIsmonotonic(input *C.VipsImage) (bool, error) { - incOpCounter("hist_ismonotonic") - - var out_monotonic C.int - - ret := C.gen_vips_hist_ismonotonic(input, &out_monotonic) - if ret != 0 { - return false, handleVipsError() - } - - return out_monotonic != 0, nil -} - -// HistLocalOptions are optional parameters for hist_local. -type HistLocalOptions struct { - MaxSlope *int -} - -// vipsGenHistLocal calls the vips hist_local operation. -// local histogram equalisation -func vipsGenHistLocal(input *C.VipsImage, width int, height int, opts *HistLocalOptions) (*C.VipsImage, error) { - incOpCounter("hist_local") - - var out_out *C.VipsImage - - var cOpts C.GenHistLocalOpts - if opts != nil { - if opts.MaxSlope != nil { - cOpts.has_maxSlope = 1 - cOpts.maxSlope = C.int(*opts.MaxSlope) - } - } - - ret := C.gen_vips_hist_local(input, C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistMatch calls the vips hist_match operation. -// match two histograms -func vipsGenHistMatch(input *C.VipsImage, ref *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("hist_match") - - var out_out *C.VipsImage - - ret := C.gen_vips_hist_match(input, ref, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistNorm calls the vips hist_norm operation. -// normalise histogram -func vipsGenHistNorm(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("hist_norm") - - var out_out *C.VipsImage - - ret := C.gen_vips_hist_norm(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenHistPlot calls the vips hist_plot operation. -// plot histogram -func vipsGenHistPlot(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("hist_plot") - - var out_out *C.VipsImage - - ret := C.gen_vips_hist_plot(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// HoughCircleOptions are optional parameters for hough_circle. -type HoughCircleOptions struct { - Scale *int - MinRadius *int - MaxRadius *int -} - -// vipsGenHoughCircle calls the vips hough_circle operation. -// find hough circle transform -func vipsGenHoughCircle(input *C.VipsImage, opts *HoughCircleOptions) (*C.VipsImage, error) { - incOpCounter("hough_circle") - - var out_out *C.VipsImage - - var cOpts C.GenHoughCircleOpts - if opts != nil { - if opts.Scale != nil { - cOpts.has_scale = 1 - cOpts.scale = C.int(*opts.Scale) - } - if opts.MinRadius != nil { - cOpts.has_minRadius = 1 - cOpts.minRadius = C.int(*opts.MinRadius) - } - if opts.MaxRadius != nil { - cOpts.has_maxRadius = 1 - cOpts.maxRadius = C.int(*opts.MaxRadius) - } - } - - ret := C.gen_vips_hough_circle(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// HoughLineOptions are optional parameters for hough_line. -type HoughLineOptions struct { - Width *int - Height *int -} - -// vipsGenHoughLine calls the vips hough_line operation. -// find hough line transform -func vipsGenHoughLine(input *C.VipsImage, opts *HoughLineOptions) (*C.VipsImage, error) { - incOpCounter("hough_line") - - var out_out *C.VipsImage - - var cOpts C.GenHoughLineOpts - if opts != nil { - if opts.Width != nil { - cOpts.has_width = 1 - cOpts.width = C.int(*opts.Width) - } - if opts.Height != nil { - cOpts.has_height = 1 - cOpts.height = C.int(*opts.Height) - } - } - - ret := C.gen_vips_hough_line(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// IccExportOptions are optional parameters for icc_export. -type IccExportOptions struct { - Pcs *int - Intent *Intent - BlackPointCompensation *bool - OutputProfile *string - Depth *int -} - -// vipsGenIccExport calls the vips icc_export operation. -// output to device with ICC profile -func vipsGenIccExport(input *C.VipsImage, opts *IccExportOptions) (*C.VipsImage, error) { - incOpCounter("icc_export") - - var out_out *C.VipsImage - - var cOpts C.GenIccExportOpts - if opts != nil { - if opts.Pcs != nil { - cOpts.has_pcs = 1 - cOpts.pcs = C.VipsPCS(*opts.Pcs) - } - if opts.Intent != nil { - cOpts.has_intent = 1 - cOpts.intent = C.VipsIntent(*opts.Intent) - } - if opts.BlackPointCompensation != nil { - cOpts.has_blackPointCompensation = 1 - cOpts.blackPointCompensation = C.int(boolToInt(*opts.BlackPointCompensation)) - } - if opts.OutputProfile != nil { - cOpts.has_outputProfile = 1 - tmp_outputProfile := C.CString(*opts.OutputProfile) - defer C.free(unsafe.Pointer(tmp_outputProfile)) - cOpts.outputProfile = tmp_outputProfile - } - if opts.Depth != nil { - cOpts.has_depth = 1 - cOpts.depth = C.int(*opts.Depth) - } - } - - ret := C.gen_vips_icc_export(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// IccImportOptions are optional parameters for icc_import. -type IccImportOptions struct { - Pcs *int - Intent *Intent - BlackPointCompensation *bool - Embedded *bool - InputProfile *string -} - -// vipsGenIccImport calls the vips icc_import operation. -// import from device with ICC profile -func vipsGenIccImport(input *C.VipsImage, opts *IccImportOptions) (*C.VipsImage, error) { - incOpCounter("icc_import") - - var out_out *C.VipsImage - - var cOpts C.GenIccImportOpts - if opts != nil { - if opts.Pcs != nil { - cOpts.has_pcs = 1 - cOpts.pcs = C.VipsPCS(*opts.Pcs) - } - if opts.Intent != nil { - cOpts.has_intent = 1 - cOpts.intent = C.VipsIntent(*opts.Intent) - } - if opts.BlackPointCompensation != nil { - cOpts.has_blackPointCompensation = 1 - cOpts.blackPointCompensation = C.int(boolToInt(*opts.BlackPointCompensation)) - } - if opts.Embedded != nil { - cOpts.has_embedded = 1 - cOpts.embedded = C.int(boolToInt(*opts.Embedded)) - } - if opts.InputProfile != nil { - cOpts.has_inputProfile = 1 - tmp_inputProfile := C.CString(*opts.InputProfile) - defer C.free(unsafe.Pointer(tmp_inputProfile)) - cOpts.inputProfile = tmp_inputProfile - } - } - - ret := C.gen_vips_icc_import(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// IdentityOptions are optional parameters for identity. -type IdentityOptions struct { - Bands *int - Ushort *bool - Size *int -} - -// vipsGenIdentity calls the vips identity operation. -// make a 1D image where pixel values are indexes -func vipsGenIdentity(opts *IdentityOptions) (*C.VipsImage, error) { - incOpCounter("identity") - - var out_out *C.VipsImage - - var cOpts C.GenIdentityOpts - if opts != nil { - if opts.Bands != nil { - cOpts.has_bands = 1 - cOpts.bands = C.int(*opts.Bands) - } - if opts.Ushort != nil { - cOpts.has_ushort = 1 - cOpts.ushort = C.int(boolToInt(*opts.Ushort)) - } - if opts.Size != nil { - cOpts.has_size = 1 - cOpts.size = C.int(*opts.Size) - } - } - - ret := C.gen_vips_identity(&out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// IfthenelseOptions are optional parameters for ifthenelse. -type IfthenelseOptions struct { - Blend *bool -} - -// vipsGenIfthenelse calls the vips ifthenelse operation. -// ifthenelse an image -func vipsGenIfthenelse(cond *C.VipsImage, in1 *C.VipsImage, in2 *C.VipsImage, opts *IfthenelseOptions) (*C.VipsImage, error) { - incOpCounter("ifthenelse") - - var out_out *C.VipsImage - - var cOpts C.GenIfthenelseOpts - if opts != nil { - if opts.Blend != nil { - cOpts.has_blend = 1 - cOpts.blend = C.int(boolToInt(*opts.Blend)) - } - } - - ret := C.gen_vips_ifthenelse(cond, in1, in2, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// InsertOptions are optional parameters for insert. -type InsertOptions struct { - Expand *bool - Background []float64 -} - -// vipsGenInsert calls the vips insert operation. -// insert image @sub into @main at @x, @y -func vipsGenInsert(main *C.VipsImage, sub *C.VipsImage, x int, y int, opts *InsertOptions) (*C.VipsImage, error) { - incOpCounter("insert") - - var out_out *C.VipsImage - - var cOpts C.GenInsertOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Expand != nil { - cOpts.has_expand = 1 - cOpts.expand = C.int(boolToInt(*opts.Expand)) - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - } - - ret := C.gen_vips_insert(main, sub, C.int(x), C.int(y), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenInvert calls the vips invert operation. -// invert an image -func vipsGenInvert(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("invert") - - var out_out *C.VipsImage - - ret := C.gen_vips_invert(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// InvertlutOptions are optional parameters for invertlut. -type InvertlutOptions struct { - Size *int -} - -// vipsGenInvertlut calls the vips invertlut operation. -// build an inverted look-up table -func vipsGenInvertlut(input *C.VipsImage, opts *InvertlutOptions) (*C.VipsImage, error) { - incOpCounter("invertlut") - - var out_out *C.VipsImage - - var cOpts C.GenInvertlutOpts - if opts != nil { - if opts.Size != nil { - cOpts.has_size = 1 - cOpts.size = C.int(*opts.Size) - } - } - - ret := C.gen_vips_invertlut(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// InvfftOptions are optional parameters for invfft. -type InvfftOptions struct { - Real *bool -} - -// vipsGenInvfft calls the vips invfft operation. -// inverse FFT -func vipsGenInvfft(input *C.VipsImage, opts *InvfftOptions) (*C.VipsImage, error) { - incOpCounter("invfft") - - var out_out *C.VipsImage - - var cOpts C.GenInvfftOpts - if opts != nil { - if opts.Real != nil { - cOpts.has_real = 1 - cOpts.real = C.int(boolToInt(*opts.Real)) - } - } - - ret := C.gen_vips_invfft(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// JoinOptions are optional parameters for join. -type JoinOptions struct { - Expand *bool - Shim *int - Background []float64 - Align *Align -} - -// vipsGenJoin calls the vips join operation. -// join a pair of images -func vipsGenJoin(in1 *C.VipsImage, in2 *C.VipsImage, direction Direction, opts *JoinOptions) (*C.VipsImage, error) { - incOpCounter("join") - - var out_out *C.VipsImage - - var cOpts C.GenJoinOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Expand != nil { - cOpts.has_expand = 1 - cOpts.expand = C.int(boolToInt(*opts.Expand)) - } - if opts.Shim != nil { - cOpts.has_shim = 1 - cOpts.shim = C.int(*opts.Shim) - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Align != nil { - cOpts.has_align = 1 - cOpts.align = C.VipsAlign(*opts.Align) - } - } - - ret := C.gen_vips_join(in1, in2, C.VipsDirection(direction), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenLabelregions calls the vips labelregions operation. -// label regions in an image -func vipsGenLabelregions(input *C.VipsImage) (*C.VipsImage, int, error) { - incOpCounter("labelregions") - - var out_mask *C.VipsImage - var out_segments C.int - - ret := C.gen_vips_labelregions(input, &out_mask, &out_segments) - if ret != 0 { - return nil, 0, handleImageError(out_mask) - } - - return out_mask, int(out_segments), nil -} - -// LinearOptions are optional parameters for linear. -type LinearOptions struct { - Uchar *bool -} - -// vipsGenLinear calls the vips linear operation. -// calculate (a * in + b) -func vipsGenLinear(input *C.VipsImage, a []float64, b []float64, opts *LinearOptions) (*C.VipsImage, error) { - incOpCounter("linear") - - var out_out *C.VipsImage - - var cOpts C.GenLinearOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - } - - ret := C.gen_vips_linear(input, (*C.double)(unsafe.Pointer(&a[0])), C.int(len(a)), (*C.double)(unsafe.Pointer(&b[0])), C.int(len(b)), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// LinecacheOptions are optional parameters for linecache. -type LinecacheOptions struct { - TileHeight *int - Access *int - Threaded *bool - Persistent *bool -} - -// vipsGenLinecache calls the vips linecache operation. -// cache an image as a set of lines -func vipsGenLinecache(input *C.VipsImage, opts *LinecacheOptions) (*C.VipsImage, error) { - incOpCounter("linecache") - - var out_out *C.VipsImage - - var cOpts C.GenLinecacheOpts - if opts != nil { - if opts.TileHeight != nil { - cOpts.has_tileHeight = 1 - cOpts.tileHeight = C.int(*opts.TileHeight) - } - if opts.Access != nil { - cOpts.has_access = 1 - cOpts.access = C.VipsAccess(*opts.Access) - } - if opts.Threaded != nil { - cOpts.has_threaded = 1 - cOpts.threaded = C.int(boolToInt(*opts.Threaded)) - } - if opts.Persistent != nil { - cOpts.has_persistent = 1 - cOpts.persistent = C.int(boolToInt(*opts.Persistent)) - } - } - - ret := C.gen_vips_linecache(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// LogmatOptions are optional parameters for logmat. -type LogmatOptions struct { - Separable *bool - Precision *Precision -} - -// vipsGenLogmat calls the vips logmat operation. -// make a Laplacian of Gaussian image -func vipsGenLogmat(sigma float64, minAmpl float64, opts *LogmatOptions) (*C.VipsImage, error) { - incOpCounter("logmat") - - var out_out *C.VipsImage - - var cOpts C.GenLogmatOpts - if opts != nil { - if opts.Separable != nil { - cOpts.has_separable = 1 - cOpts.separable = C.int(boolToInt(*opts.Separable)) - } - if opts.Precision != nil { - cOpts.has_precision = 1 - cOpts.precision = C.VipsPrecision(*opts.Precision) - } - } - - ret := C.gen_vips_logmat(C.double(sigma), C.double(minAmpl), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MapimOptions are optional parameters for mapim. -type MapimOptions struct { - Interpolate *C.VipsInterpolate - Background []float64 - Premultiplied *bool - Extend *ExtendStrategy -} - -// vipsGenMapim calls the vips mapim operation. -// resample with a map image -func vipsGenMapim(input *C.VipsImage, index *C.VipsImage, opts *MapimOptions) (*C.VipsImage, error) { - incOpCounter("mapim") - - var out_out *C.VipsImage - - var cOpts C.GenMapimOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Premultiplied != nil { - cOpts.has_premultiplied = 1 - cOpts.premultiplied = C.int(boolToInt(*opts.Premultiplied)) - } - if opts.Extend != nil { - cOpts.has_extend = 1 - cOpts.extend = C.VipsExtend(*opts.Extend) - } - } - - ret := C.gen_vips_mapim(input, index, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaplutOptions are optional parameters for maplut. -type MaplutOptions struct { - Band *int -} - -// vipsGenMaplut calls the vips maplut operation. -// map an image though a lut -func vipsGenMaplut(input *C.VipsImage, lut *C.VipsImage, opts *MaplutOptions) (*C.VipsImage, error) { - incOpCounter("maplut") - - var out_out *C.VipsImage - - var cOpts C.GenMaplutOpts - if opts != nil { - if opts.Band != nil { - cOpts.has_band = 1 - cOpts.band = C.int(*opts.Band) - } - } - - ret := C.gen_vips_maplut(input, lut, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskButterworthOptions are optional parameters for mask_butterworth. -type MaskButterworthOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskButterworth calls the vips mask_butterworth operation. -// make a butterworth filter -func vipsGenMaskButterworth(width int, height int, order float64, frequencyCutoff float64, amplitudeCutoff float64, opts *MaskButterworthOptions) (*C.VipsImage, error) { - incOpCounter("mask_butterworth") - - var out_out *C.VipsImage - - var cOpts C.GenMaskButterworthOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_butterworth(C.int(width), C.int(height), C.double(order), C.double(frequencyCutoff), C.double(amplitudeCutoff), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskButterworthBandOptions are optional parameters for mask_butterworth_band. -type MaskButterworthBandOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskButterworthBand calls the vips mask_butterworth_band operation. -// make a butterworth_band filter -func vipsGenMaskButterworthBand(width int, height int, order float64, frequencyCutoffX float64, frequencyCutoffY float64, radius float64, amplitudeCutoff float64, opts *MaskButterworthBandOptions) (*C.VipsImage, error) { - incOpCounter("mask_butterworth_band") - - var out_out *C.VipsImage - - var cOpts C.GenMaskButterworthBandOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_butterworth_band(C.int(width), C.int(height), C.double(order), C.double(frequencyCutoffX), C.double(frequencyCutoffY), C.double(radius), C.double(amplitudeCutoff), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskButterworthRingOptions are optional parameters for mask_butterworth_ring. -type MaskButterworthRingOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskButterworthRing calls the vips mask_butterworth_ring operation. -// make a butterworth ring filter -func vipsGenMaskButterworthRing(width int, height int, order float64, frequencyCutoff float64, amplitudeCutoff float64, ringwidth float64, opts *MaskButterworthRingOptions) (*C.VipsImage, error) { - incOpCounter("mask_butterworth_ring") - - var out_out *C.VipsImage - - var cOpts C.GenMaskButterworthRingOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_butterworth_ring(C.int(width), C.int(height), C.double(order), C.double(frequencyCutoff), C.double(amplitudeCutoff), C.double(ringwidth), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskFractalOptions are optional parameters for mask_fractal. -type MaskFractalOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskFractal calls the vips mask_fractal operation. -// make fractal filter -func vipsGenMaskFractal(width int, height int, fractalDimension float64, opts *MaskFractalOptions) (*C.VipsImage, error) { - incOpCounter("mask_fractal") - - var out_out *C.VipsImage - - var cOpts C.GenMaskFractalOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_fractal(C.int(width), C.int(height), C.double(fractalDimension), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskGaussianOptions are optional parameters for mask_gaussian. -type MaskGaussianOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskGaussian calls the vips mask_gaussian operation. -// make a gaussian filter -func vipsGenMaskGaussian(width int, height int, frequencyCutoff float64, amplitudeCutoff float64, opts *MaskGaussianOptions) (*C.VipsImage, error) { - incOpCounter("mask_gaussian") - - var out_out *C.VipsImage - - var cOpts C.GenMaskGaussianOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_gaussian(C.int(width), C.int(height), C.double(frequencyCutoff), C.double(amplitudeCutoff), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskGaussianBandOptions are optional parameters for mask_gaussian_band. -type MaskGaussianBandOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskGaussianBand calls the vips mask_gaussian_band operation. -// make a gaussian filter -func vipsGenMaskGaussianBand(width int, height int, frequencyCutoffX float64, frequencyCutoffY float64, radius float64, amplitudeCutoff float64, opts *MaskGaussianBandOptions) (*C.VipsImage, error) { - incOpCounter("mask_gaussian_band") - - var out_out *C.VipsImage - - var cOpts C.GenMaskGaussianBandOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_gaussian_band(C.int(width), C.int(height), C.double(frequencyCutoffX), C.double(frequencyCutoffY), C.double(radius), C.double(amplitudeCutoff), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskGaussianRingOptions are optional parameters for mask_gaussian_ring. -type MaskGaussianRingOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskGaussianRing calls the vips mask_gaussian_ring operation. -// make a gaussian ring filter -func vipsGenMaskGaussianRing(width int, height int, frequencyCutoff float64, amplitudeCutoff float64, ringwidth float64, opts *MaskGaussianRingOptions) (*C.VipsImage, error) { - incOpCounter("mask_gaussian_ring") - - var out_out *C.VipsImage - - var cOpts C.GenMaskGaussianRingOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_gaussian_ring(C.int(width), C.int(height), C.double(frequencyCutoff), C.double(amplitudeCutoff), C.double(ringwidth), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskIdealOptions are optional parameters for mask_ideal. -type MaskIdealOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskIdeal calls the vips mask_ideal operation. -// make an ideal filter -func vipsGenMaskIdeal(width int, height int, frequencyCutoff float64, opts *MaskIdealOptions) (*C.VipsImage, error) { - incOpCounter("mask_ideal") - - var out_out *C.VipsImage - - var cOpts C.GenMaskIdealOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_ideal(C.int(width), C.int(height), C.double(frequencyCutoff), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskIdealBandOptions are optional parameters for mask_ideal_band. -type MaskIdealBandOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskIdealBand calls the vips mask_ideal_band operation. -// make an ideal band filter -func vipsGenMaskIdealBand(width int, height int, frequencyCutoffX float64, frequencyCutoffY float64, radius float64, opts *MaskIdealBandOptions) (*C.VipsImage, error) { - incOpCounter("mask_ideal_band") - - var out_out *C.VipsImage - - var cOpts C.GenMaskIdealBandOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_ideal_band(C.int(width), C.int(height), C.double(frequencyCutoffX), C.double(frequencyCutoffY), C.double(radius), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MaskIdealRingOptions are optional parameters for mask_ideal_ring. -type MaskIdealRingOptions struct { - Uchar *bool - Nodc *bool - Reject *bool - Optical *bool -} - -// vipsGenMaskIdealRing calls the vips mask_ideal_ring operation. -// make an ideal ring filter -func vipsGenMaskIdealRing(width int, height int, frequencyCutoff float64, ringwidth float64, opts *MaskIdealRingOptions) (*C.VipsImage, error) { - incOpCounter("mask_ideal_ring") - - var out_out *C.VipsImage - - var cOpts C.GenMaskIdealRingOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Nodc != nil { - cOpts.has_nodc = 1 - cOpts.nodc = C.int(boolToInt(*opts.Nodc)) - } - if opts.Reject != nil { - cOpts.has_reject = 1 - cOpts.reject = C.int(boolToInt(*opts.Reject)) - } - if opts.Optical != nil { - cOpts.has_optical = 1 - cOpts.optical = C.int(boolToInt(*opts.Optical)) - } - } - - ret := C.gen_vips_mask_ideal_ring(C.int(width), C.int(height), C.double(frequencyCutoff), C.double(ringwidth), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MatchOptions are optional parameters for match. -type MatchOptions struct { - Hwindow *int - Harea *int - Search *bool - Interpolate *C.VipsInterpolate -} - -// vipsGenMatch calls the vips match operation. -// first-order match of two images -func vipsGenMatch(ref *C.VipsImage, sec *C.VipsImage, xr1 int, yr1 int, xs1 int, ys1 int, xr2 int, yr2 int, xs2 int, ys2 int, opts *MatchOptions) (*C.VipsImage, error) { - incOpCounter("match") - - var out_out *C.VipsImage - - var cOpts C.GenMatchOpts - if opts != nil { - if opts.Hwindow != nil { - cOpts.has_hwindow = 1 - cOpts.hwindow = C.int(*opts.Hwindow) - } - if opts.Harea != nil { - cOpts.has_harea = 1 - cOpts.harea = C.int(*opts.Harea) - } - if opts.Search != nil { - cOpts.has_search = 1 - cOpts.search = C.int(boolToInt(*opts.Search)) - } - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - } - - ret := C.gen_vips_match(ref, sec, C.int(xr1), C.int(yr1), C.int(xs1), C.int(ys1), C.int(xr2), C.int(yr2), C.int(xs2), C.int(ys2), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMath calls the vips math operation. -// apply a math operation to an image -func vipsGenMath(input *C.VipsImage, math OperationMath) (*C.VipsImage, error) { - incOpCounter("math") - - var out_out *C.VipsImage - - ret := C.gen_vips_math(input, C.VipsOperationMath(math), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMath2 calls the vips math2 operation. -// binary math operations -func vipsGenMath2(left *C.VipsImage, right *C.VipsImage, math2 OperationMath2) (*C.VipsImage, error) { - incOpCounter("math2") - - var out_out *C.VipsImage - - ret := C.gen_vips_math2(left, right, C.VipsOperationMath2(math2), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMath2Const calls the vips math2_const operation. -// binary math operations with a constant -func vipsGenMath2Const(input *C.VipsImage, math2 OperationMath2, c []float64) (*C.VipsImage, error) { - incOpCounter("math2_const") - - var out_out *C.VipsImage - - ret := C.gen_vips_math2_const(input, C.VipsOperationMath2(math2), (*C.double)(unsafe.Pointer(&c[0])), C.int(len(c)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMatrixinvert calls the vips matrixinvert operation. -// invert a matrix -func vipsGenMatrixinvert(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("matrixinvert") - - var out_out *C.VipsImage - - ret := C.gen_vips_matrixinvert(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMatrixmultiply calls the vips matrixmultiply operation. -// multiply two matrices -func vipsGenMatrixmultiply(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("matrixmultiply") - - var out_out *C.VipsImage - - ret := C.gen_vips_matrixmultiply(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMaxpair calls the vips maxpair operation. -// maximum of a pair of images -func vipsGenMaxpair(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("maxpair") - - var out_out *C.VipsImage - - ret := C.gen_vips_maxpair(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MergeOptions are optional parameters for merge. -type MergeOptions struct { - Mblend *int -} - -// vipsGenMerge calls the vips merge operation. -// merge two images -func vipsGenMerge(ref *C.VipsImage, sec *C.VipsImage, direction Direction, dx int, dy int, opts *MergeOptions) (*C.VipsImage, error) { - incOpCounter("merge") - - var out_out *C.VipsImage - - var cOpts C.GenMergeOpts - if opts != nil { - if opts.Mblend != nil { - cOpts.has_mblend = 1 - cOpts.mblend = C.int(*opts.Mblend) - } - } - - ret := C.gen_vips_merge(ref, sec, C.VipsDirection(direction), C.int(dx), C.int(dy), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMinpair calls the vips minpair operation. -// minimum of a pair of images -func vipsGenMinpair(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("minpair") - - var out_out *C.VipsImage - - ret := C.gen_vips_minpair(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMorph calls the vips morph operation. -// morphology operation -func vipsGenMorph(input *C.VipsImage, mask *C.VipsImage, morph OperationMorphology) (*C.VipsImage, error) { - incOpCounter("morph") - - var out_out *C.VipsImage - - ret := C.gen_vips_morph(input, mask, C.VipsOperationMorphology(morph), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MosaicOptions are optional parameters for mosaic. -type MosaicOptions struct { - Hwindow *int - Harea *int - Mblend *int - Bandno *int -} - -// vipsGenMosaic calls the vips mosaic operation. -// mosaic two images -func vipsGenMosaic(ref *C.VipsImage, sec *C.VipsImage, direction Direction, xref int, yref int, xsec int, ysec int, opts *MosaicOptions) (*C.VipsImage, int, int, float64, float64, float64, float64, error) { - incOpCounter("mosaic") - - var out_out *C.VipsImage - var out_dx0 C.int - var out_dy0 C.int - var out_scale1 C.double - var out_angle1 C.double - var out_dy1 C.double - var out_dx1 C.double - - var cOpts C.GenMosaicOpts - if opts != nil { - if opts.Hwindow != nil { - cOpts.has_hwindow = 1 - cOpts.hwindow = C.int(*opts.Hwindow) - } - if opts.Harea != nil { - cOpts.has_harea = 1 - cOpts.harea = C.int(*opts.Harea) - } - if opts.Mblend != nil { - cOpts.has_mblend = 1 - cOpts.mblend = C.int(*opts.Mblend) - } - if opts.Bandno != nil { - cOpts.has_bandno = 1 - cOpts.bandno = C.int(*opts.Bandno) - } - } - - ret := C.gen_vips_mosaic(ref, sec, C.VipsDirection(direction), C.int(xref), C.int(yref), C.int(xsec), C.int(ysec), &out_out, &out_dx0, &out_dy0, &out_scale1, &out_angle1, &out_dy1, &out_dx1, &cOpts) - if ret != 0 { - return nil, 0, 0, 0, 0, 0, 0, handleImageError(out_out) - } - - return out_out, int(out_dx0), int(out_dy0), float64(out_scale1), float64(out_angle1), float64(out_dy1), float64(out_dx1), nil -} - -// Mosaic1Options are optional parameters for mosaic1. -type Mosaic1Options struct { - Hwindow *int - Harea *int - Search *bool - Interpolate *C.VipsInterpolate - Mblend *int -} - -// vipsGenMosaic1 calls the vips mosaic1 operation. -// first-order mosaic of two images -func vipsGenMosaic1(ref *C.VipsImage, sec *C.VipsImage, direction Direction, xr1 int, yr1 int, xs1 int, ys1 int, xr2 int, yr2 int, xs2 int, ys2 int, opts *Mosaic1Options) (*C.VipsImage, error) { - incOpCounter("mosaic1") - - var out_out *C.VipsImage - - var cOpts C.GenMosaic1Opts - if opts != nil { - if opts.Hwindow != nil { - cOpts.has_hwindow = 1 - cOpts.hwindow = C.int(*opts.Hwindow) - } - if opts.Harea != nil { - cOpts.has_harea = 1 - cOpts.harea = C.int(*opts.Harea) - } - if opts.Search != nil { - cOpts.has_search = 1 - cOpts.search = C.int(boolToInt(*opts.Search)) - } - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - if opts.Mblend != nil { - cOpts.has_mblend = 1 - cOpts.mblend = C.int(*opts.Mblend) - } - } - - ret := C.gen_vips_mosaic1(ref, sec, C.VipsDirection(direction), C.int(xr1), C.int(yr1), C.int(xs1), C.int(ys1), C.int(xr2), C.int(yr2), C.int(xs2), C.int(ys2), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// MsbOptions are optional parameters for msb. -type MsbOptions struct { - Band *int -} - -// vipsGenMsb calls the vips msb operation. -// pick most-significant byte from an image -func vipsGenMsb(input *C.VipsImage, opts *MsbOptions) (*C.VipsImage, error) { - incOpCounter("msb") - - var out_out *C.VipsImage - - var cOpts C.GenMsbOpts - if opts != nil { - if opts.Band != nil { - cOpts.has_band = 1 - cOpts.band = C.int(*opts.Band) - } - } - - ret := C.gen_vips_msb(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenMultiply calls the vips multiply operation. -// multiply two images -func vipsGenMultiply(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("multiply") - - var out_out *C.VipsImage - - ret := C.gen_vips_multiply(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenPercent calls the vips percent operation. -// find threshold for percent of pixels -func vipsGenPercent(input *C.VipsImage, percent float64) (int, error) { - incOpCounter("percent") - - var out_threshold C.int - - ret := C.gen_vips_percent(input, C.double(percent), &out_threshold) - if ret != 0 { - return 0, handleVipsError() - } - - return int(out_threshold), nil -} - -// PerlinOptions are optional parameters for perlin. -type PerlinOptions struct { - CellSize *int - Uchar *bool - Seed *int -} - -// vipsGenPerlin calls the vips perlin operation. -// make a perlin noise image -func vipsGenPerlin(width int, height int, opts *PerlinOptions) (*C.VipsImage, error) { - incOpCounter("perlin") - - var out_out *C.VipsImage - - var cOpts C.GenPerlinOpts - if opts != nil { - if opts.CellSize != nil { - cOpts.has_cellSize = 1 - cOpts.cellSize = C.int(*opts.CellSize) - } - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Seed != nil { - cOpts.has_seed = 1 - cOpts.seed = C.int(*opts.Seed) - } - } - - ret := C.gen_vips_perlin(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenPhasecor calls the vips phasecor operation. -// calculate phase correlation -func vipsGenPhasecor(input *C.VipsImage, in2 *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("phasecor") - - var out_out *C.VipsImage - - ret := C.gen_vips_phasecor(input, in2, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// PremultiplyOptions are optional parameters for premultiply. -type PremultiplyOptions struct { - MaxAlpha *float64 -} - -// vipsGenPremultiply calls the vips premultiply operation. -// premultiply image alpha -func vipsGenPremultiply(input *C.VipsImage, opts *PremultiplyOptions) (*C.VipsImage, error) { - incOpCounter("premultiply") - - var out_out *C.VipsImage - - var cOpts C.GenPremultiplyOpts - if opts != nil { - if opts.MaxAlpha != nil { - cOpts.has_maxAlpha = 1 - cOpts.maxAlpha = C.double(*opts.MaxAlpha) - } - } - - ret := C.gen_vips_premultiply(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenPrewitt calls the vips prewitt operation. -// Prewitt edge detector -func vipsGenPrewitt(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("prewitt") - - var out_out *C.VipsImage - - ret := C.gen_vips_prewitt(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenProfile calls the vips profile operation. -// find image profiles -func vipsGenProfile(input *C.VipsImage) (*C.VipsImage, *C.VipsImage, error) { - incOpCounter("profile") - - var out_columns *C.VipsImage - var out_rows *C.VipsImage - - ret := C.gen_vips_profile(input, &out_columns, &out_rows) - if ret != 0 { - return nil, nil, handleImageError(out_columns) - } - - return out_columns, out_rows, nil -} - -// vipsGenProject calls the vips project operation. -// find image projections -func vipsGenProject(input *C.VipsImage) (*C.VipsImage, *C.VipsImage, error) { - incOpCounter("project") - - var out_columns *C.VipsImage - var out_rows *C.VipsImage - - ret := C.gen_vips_project(input, &out_columns, &out_rows) - if ret != 0 { - return nil, nil, handleImageError(out_columns) - } - - return out_columns, out_rows, nil -} - -// QuadraticOptions are optional parameters for quadratic. -type QuadraticOptions struct { - Interpolate *C.VipsInterpolate -} - -// vipsGenQuadratic calls the vips quadratic operation. -// resample an image with a quadratic transform -func vipsGenQuadratic(input *C.VipsImage, coeff *C.VipsImage, opts *QuadraticOptions) (*C.VipsImage, error) { - incOpCounter("quadratic") - - var out_out *C.VipsImage - - var cOpts C.GenQuadraticOpts - if opts != nil { - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - } - - ret := C.gen_vips_quadratic(input, coeff, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRad2float calls the vips rad2float operation. -// unpack Radiance coding to float RGB -func vipsGenRad2float(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("rad2float") - - var out_out *C.VipsImage - - ret := C.gen_vips_rad2float(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRank calls the vips rank operation. -// rank filter -func vipsGenRank(input *C.VipsImage, width int, height int, index int) (*C.VipsImage, error) { - incOpCounter("rank") - - var out_out *C.VipsImage - - ret := C.gen_vips_rank(input, C.int(width), C.int(height), C.int(index), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRecomb calls the vips recomb operation. -// linear recombination with matrix -func vipsGenRecomb(input *C.VipsImage, m *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("recomb") - - var out_out *C.VipsImage - - ret := C.gen_vips_recomb(input, m, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ReduceOptions are optional parameters for reduce. -type ReduceOptions struct { - Kernel *Kernel - Gap *float64 -} - -// vipsGenReduce calls the vips reduce operation. -// reduce an image -func vipsGenReduce(input *C.VipsImage, hshrink float64, vshrink float64, opts *ReduceOptions) (*C.VipsImage, error) { - incOpCounter("reduce") - - var out_out *C.VipsImage - - var cOpts C.GenReduceOpts - if opts != nil { - if opts.Kernel != nil { - cOpts.has_kernel = 1 - cOpts.kernel = C.VipsKernel(*opts.Kernel) - } - if opts.Gap != nil { - cOpts.has_gap = 1 - cOpts.gap = C.double(*opts.Gap) - } - } - - ret := C.gen_vips_reduce(input, C.double(hshrink), C.double(vshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ReducehOptions are optional parameters for reduceh. -type ReducehOptions struct { - Kernel *Kernel - Gap *float64 -} - -// vipsGenReduceh calls the vips reduceh operation. -// shrink an image horizontally -func vipsGenReduceh(input *C.VipsImage, hshrink float64, opts *ReducehOptions) (*C.VipsImage, error) { - incOpCounter("reduceh") - - var out_out *C.VipsImage - - var cOpts C.GenReducehOpts - if opts != nil { - if opts.Kernel != nil { - cOpts.has_kernel = 1 - cOpts.kernel = C.VipsKernel(*opts.Kernel) - } - if opts.Gap != nil { - cOpts.has_gap = 1 - cOpts.gap = C.double(*opts.Gap) - } - } - - ret := C.gen_vips_reduceh(input, C.double(hshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ReducevOptions are optional parameters for reducev. -type ReducevOptions struct { - Kernel *Kernel - Gap *float64 -} - -// vipsGenReducev calls the vips reducev operation. -// shrink an image vertically -func vipsGenReducev(input *C.VipsImage, vshrink float64, opts *ReducevOptions) (*C.VipsImage, error) { - incOpCounter("reducev") - - var out_out *C.VipsImage - - var cOpts C.GenReducevOpts - if opts != nil { - if opts.Kernel != nil { - cOpts.has_kernel = 1 - cOpts.kernel = C.VipsKernel(*opts.Kernel) - } - if opts.Gap != nil { - cOpts.has_gap = 1 - cOpts.gap = C.double(*opts.Gap) - } - } - - ret := C.gen_vips_reducev(input, C.double(vshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRelational calls the vips relational operation. -// relational operation on two images -func vipsGenRelational(left *C.VipsImage, right *C.VipsImage, relational OperationRelational) (*C.VipsImage, error) { - incOpCounter("relational") - - var out_out *C.VipsImage - - ret := C.gen_vips_relational(left, right, C.VipsOperationRelational(relational), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRelationalConst calls the vips relational_const operation. -// relational operations against a constant -func vipsGenRelationalConst(input *C.VipsImage, relational OperationRelational, c []float64) (*C.VipsImage, error) { - incOpCounter("relational_const") - - var out_out *C.VipsImage - - ret := C.gen_vips_relational_const(input, C.VipsOperationRelational(relational), (*C.double)(unsafe.Pointer(&c[0])), C.int(len(c)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRemainder calls the vips remainder operation. -// remainder after integer division of two images -func vipsGenRemainder(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("remainder") - - var out_out *C.VipsImage - - ret := C.gen_vips_remainder(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRemainderConst calls the vips remainder_const operation. -// remainder after integer division of an image and a constant -func vipsGenRemainderConst(input *C.VipsImage, c []float64) (*C.VipsImage, error) { - incOpCounter("remainder_const") - - var out_out *C.VipsImage - - ret := C.gen_vips_remainder_const(input, (*C.double)(unsafe.Pointer(&c[0])), C.int(len(c)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRemosaic calls the vips remosaic operation. -// rebuild an mosaiced image -func vipsGenRemosaic(input *C.VipsImage, oldStr string, newStr string) (*C.VipsImage, error) { - incOpCounter("remosaic") - - cStr_oldStr := C.CString(oldStr) - defer C.free(unsafe.Pointer(cStr_oldStr)) - cStr_newStr := C.CString(newStr) - defer C.free(unsafe.Pointer(cStr_newStr)) - var out_out *C.VipsImage - - ret := C.gen_vips_remosaic(input, cStr_oldStr, cStr_newStr, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenReplicate calls the vips replicate operation. -// replicate an image -func vipsGenReplicate(input *C.VipsImage, across int, down int) (*C.VipsImage, error) { - incOpCounter("replicate") - - var out_out *C.VipsImage - - ret := C.gen_vips_replicate(input, C.int(across), C.int(down), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRot calls the vips rot operation. -// rotate an image -func vipsGenRot(input *C.VipsImage, angle Angle) (*C.VipsImage, error) { - incOpCounter("rot") - - var out_out *C.VipsImage - - ret := C.gen_vips_rot(input, C.VipsAngle(angle), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// Rot45Options are optional parameters for rot45. -type Rot45Options struct { - Angle *Angle45 -} - -// vipsGenRot45 calls the vips rot45 operation. -// rotate an image -func vipsGenRot45(input *C.VipsImage, opts *Rot45Options) (*C.VipsImage, error) { - incOpCounter("rot45") - - var out_out *C.VipsImage - - var cOpts C.GenRot45Opts - if opts != nil { - if opts.Angle != nil { - cOpts.has_angle = 1 - cOpts.angle = C.VipsAngle45(*opts.Angle) - } - } - - ret := C.gen_vips_rot45(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// RotateOptions are optional parameters for rotate. -type RotateOptions struct { - Interpolate *C.VipsInterpolate - Background []float64 - Odx *float64 - Ody *float64 - Idx *float64 - Idy *float64 -} - -// vipsGenRotate calls the vips rotate operation. -// rotate an image by a number of degrees -func vipsGenRotate(input *C.VipsImage, angle float64, opts *RotateOptions) (*C.VipsImage, error) { - incOpCounter("rotate") - - var out_out *C.VipsImage - - var cOpts C.GenRotateOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Odx != nil { - cOpts.has_odx = 1 - cOpts.odx = C.double(*opts.Odx) - } - if opts.Ody != nil { - cOpts.has_ody = 1 - cOpts.ody = C.double(*opts.Ody) - } - if opts.Idx != nil { - cOpts.has_idx = 1 - cOpts.idx = C.double(*opts.Idx) - } - if opts.Idy != nil { - cOpts.has_idy = 1 - cOpts.idy = C.double(*opts.Idy) - } - } - - ret := C.gen_vips_rotate(input, C.double(angle), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenRound calls the vips round operation. -// perform a round function on an image -func vipsGenRound(input *C.VipsImage, round OperationRound) (*C.VipsImage, error) { - incOpCounter("round") - - var out_out *C.VipsImage - - ret := C.gen_vips_round(input, C.VipsOperationRound(round), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSRGB2HSV calls the vips sRGB2HSV operation. -// transform sRGB to HSV -func vipsGenSRGB2HSV(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("sRGB2HSV") - - var out_out *C.VipsImage - - ret := C.gen_vips_sRGB2HSV(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSRGB2scRGB calls the vips sRGB2scRGB operation. -// convert an sRGB image to scRGB -func vipsGenSRGB2scRGB(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("sRGB2scRGB") - - var out_out *C.VipsImage - - ret := C.gen_vips_sRGB2scRGB(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ScRGB2BWOptions are optional parameters for scRGB2BW. -type ScRGB2BWOptions struct { - Depth *int -} - -// vipsGenScRGB2BW calls the vips scRGB2BW operation. -// convert scRGB to BW -func vipsGenScRGB2BW(input *C.VipsImage, opts *ScRGB2BWOptions) (*C.VipsImage, error) { - incOpCounter("scRGB2BW") - - var out_out *C.VipsImage - - var cOpts C.GenScRGB2BWOpts - if opts != nil { - if opts.Depth != nil { - cOpts.has_depth = 1 - cOpts.depth = C.int(*opts.Depth) - } - } - - ret := C.gen_vips_scRGB2BW(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenScRGB2XYZ calls the vips scRGB2XYZ operation. -// transform scRGB to XYZ -func vipsGenScRGB2XYZ(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("scRGB2XYZ") - - var out_out *C.VipsImage - - ret := C.gen_vips_scRGB2XYZ(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ScRGB2sRGBOptions are optional parameters for scRGB2sRGB. -type ScRGB2sRGBOptions struct { - Depth *int -} - -// vipsGenScRGB2sRGB calls the vips scRGB2sRGB operation. -// convert scRGB to sRGB -func vipsGenScRGB2sRGB(input *C.VipsImage, opts *ScRGB2sRGBOptions) (*C.VipsImage, error) { - incOpCounter("scRGB2sRGB") - - var out_out *C.VipsImage - - var cOpts C.GenScRGB2sRGBOpts - if opts != nil { - if opts.Depth != nil { - cOpts.has_depth = 1 - cOpts.depth = C.int(*opts.Depth) - } - } - - ret := C.gen_vips_scRGB2sRGB(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ScaleOptions are optional parameters for scale. -type ScaleOptions struct { - Exp *float64 - Log *bool -} - -// vipsGenScale calls the vips scale operation. -// scale an image to uchar -func vipsGenScale(input *C.VipsImage, opts *ScaleOptions) (*C.VipsImage, error) { - incOpCounter("scale") - - var out_out *C.VipsImage - - var cOpts C.GenScaleOpts - if opts != nil { - if opts.Exp != nil { - cOpts.has_exp = 1 - cOpts.exp = C.double(*opts.Exp) - } - if opts.Log != nil { - cOpts.has_log = 1 - cOpts.log = C.int(boolToInt(*opts.Log)) - } - } - - ret := C.gen_vips_scale(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenScharr calls the vips scharr operation. -// Scharr edge detector -func vipsGenScharr(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("scharr") - - var out_out *C.VipsImage - - ret := C.gen_vips_scharr(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SequentialOptions are optional parameters for sequential. -type SequentialOptions struct { - TileHeight *int -} - -// vipsGenSequential calls the vips sequential operation. -// check sequential access -func vipsGenSequential(input *C.VipsImage, opts *SequentialOptions) (*C.VipsImage, error) { - incOpCounter("sequential") - - var out_out *C.VipsImage - - var cOpts C.GenSequentialOpts - if opts != nil { - if opts.TileHeight != nil { - cOpts.has_tileHeight = 1 - cOpts.tileHeight = C.int(*opts.TileHeight) - } - } - - ret := C.gen_vips_sequential(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SharpenOptions are optional parameters for sharpen. -type SharpenOptions struct { - Sigma *float64 - X1 *float64 - Y2 *float64 - Y3 *float64 - M1 *float64 - M2 *float64 -} - -// vipsGenSharpen calls the vips sharpen operation. -// unsharp masking for print -func vipsGenSharpen(input *C.VipsImage, opts *SharpenOptions) (*C.VipsImage, error) { - incOpCounter("sharpen") - - var out_out *C.VipsImage - - var cOpts C.GenSharpenOpts - if opts != nil { - if opts.Sigma != nil { - cOpts.has_sigma = 1 - cOpts.sigma = C.double(*opts.Sigma) - } - if opts.X1 != nil { - cOpts.has_x1 = 1 - cOpts.x1 = C.double(*opts.X1) - } - if opts.Y2 != nil { - cOpts.has_y2 = 1 - cOpts.y2 = C.double(*opts.Y2) - } - if opts.Y3 != nil { - cOpts.has_y3 = 1 - cOpts.y3 = C.double(*opts.Y3) - } - if opts.M1 != nil { - cOpts.has_m1 = 1 - cOpts.m1 = C.double(*opts.M1) - } - if opts.M2 != nil { - cOpts.has_m2 = 1 - cOpts.m2 = C.double(*opts.M2) - } - } - - ret := C.gen_vips_sharpen(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ShrinkOptions are optional parameters for shrink. -type ShrinkOptions struct { - Ceil *bool -} - -// vipsGenShrink calls the vips shrink operation. -// shrink an image -func vipsGenShrink(input *C.VipsImage, hshrink float64, vshrink float64, opts *ShrinkOptions) (*C.VipsImage, error) { - incOpCounter("shrink") - - var out_out *C.VipsImage - - var cOpts C.GenShrinkOpts - if opts != nil { - if opts.Ceil != nil { - cOpts.has_ceil = 1 - cOpts.ceil = C.int(boolToInt(*opts.Ceil)) - } - } - - ret := C.gen_vips_shrink(input, C.double(hshrink), C.double(vshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ShrinkhOptions are optional parameters for shrinkh. -type ShrinkhOptions struct { - Ceil *bool -} - -// vipsGenShrinkh calls the vips shrinkh operation. -// shrink an image horizontally -func vipsGenShrinkh(input *C.VipsImage, hshrink int, opts *ShrinkhOptions) (*C.VipsImage, error) { - incOpCounter("shrinkh") - - var out_out *C.VipsImage - - var cOpts C.GenShrinkhOpts - if opts != nil { - if opts.Ceil != nil { - cOpts.has_ceil = 1 - cOpts.ceil = C.int(boolToInt(*opts.Ceil)) - } - } - - ret := C.gen_vips_shrinkh(input, C.int(hshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ShrinkvOptions are optional parameters for shrinkv. -type ShrinkvOptions struct { - Ceil *bool -} - -// vipsGenShrinkv calls the vips shrinkv operation. -// shrink an image vertically -func vipsGenShrinkv(input *C.VipsImage, vshrink int, opts *ShrinkvOptions) (*C.VipsImage, error) { - incOpCounter("shrinkv") - - var out_out *C.VipsImage - - var cOpts C.GenShrinkvOpts - if opts != nil { - if opts.Ceil != nil { - cOpts.has_ceil = 1 - cOpts.ceil = C.int(boolToInt(*opts.Ceil)) - } - } - - ret := C.gen_vips_shrinkv(input, C.int(vshrink), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSign calls the vips sign operation. -// unit vector of pixel -func vipsGenSign(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("sign") - - var out_out *C.VipsImage - - ret := C.gen_vips_sign(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SimilarityOptions are optional parameters for similarity. -type SimilarityOptions struct { - Scale *float64 - Angle *float64 - Interpolate *C.VipsInterpolate - Background []float64 - Odx *float64 - Ody *float64 - Idx *float64 - Idy *float64 -} - -// vipsGenSimilarity calls the vips similarity operation. -// similarity transform of an image -func vipsGenSimilarity(input *C.VipsImage, opts *SimilarityOptions) (*C.VipsImage, error) { - incOpCounter("similarity") - - var out_out *C.VipsImage - - var cOpts C.GenSimilarityOpts - var pinner runtime.Pinner - defer pinner.Unpin() - if opts != nil { - if opts.Scale != nil { - cOpts.has_scale = 1 - cOpts.scale = C.double(*opts.Scale) - } - if opts.Angle != nil { - cOpts.has_angle = 1 - cOpts.angle = C.double(*opts.Angle) - } - if opts.Interpolate != nil { - cOpts.has_interpolate = 1 - cOpts.interpolate = opts.Interpolate - } - if opts.Background != nil { - cOpts.has_background = 1 - pinner.Pin(&opts.Background[0]) - cOpts.background = (*C.double)(unsafe.Pointer(&opts.Background[0])) - cOpts.background_n = C.int(len(opts.Background)) - } - if opts.Odx != nil { - cOpts.has_odx = 1 - cOpts.odx = C.double(*opts.Odx) - } - if opts.Ody != nil { - cOpts.has_ody = 1 - cOpts.ody = C.double(*opts.Ody) - } - if opts.Idx != nil { - cOpts.has_idx = 1 - cOpts.idx = C.double(*opts.Idx) - } - if opts.Idy != nil { - cOpts.has_idy = 1 - cOpts.idy = C.double(*opts.Idy) - } - } - - ret := C.gen_vips_similarity(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SinesOptions are optional parameters for sines. -type SinesOptions struct { - Uchar *bool - Hfreq *float64 - Vfreq *float64 -} - -// vipsGenSines calls the vips sines operation. -// make a 2D sine wave -func vipsGenSines(width int, height int, opts *SinesOptions) (*C.VipsImage, error) { - incOpCounter("sines") - - var out_out *C.VipsImage - - var cOpts C.GenSinesOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - if opts.Hfreq != nil { - cOpts.has_hfreq = 1 - cOpts.hfreq = C.double(*opts.Hfreq) - } - if opts.Vfreq != nil { - cOpts.has_vfreq = 1 - cOpts.vfreq = C.double(*opts.Vfreq) - } - } - - ret := C.gen_vips_sines(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SmartcropOptions are optional parameters for smartcrop. -type SmartcropOptions struct { - Interesting *Interesting - Premultiplied *bool -} - -// vipsGenSmartcrop calls the vips smartcrop operation. -// extract an area from an image -func vipsGenSmartcrop(input *C.VipsImage, width int, height int, opts *SmartcropOptions) (int, *C.VipsImage, int, error) { - incOpCounter("smartcrop") - - var out_attentionX C.int - var out_out *C.VipsImage - var out_attentionY C.int - - var cOpts C.GenSmartcropOpts - if opts != nil { - if opts.Interesting != nil { - cOpts.has_interesting = 1 - cOpts.interesting = C.VipsInteresting(*opts.Interesting) - } - if opts.Premultiplied != nil { - cOpts.has_premultiplied = 1 - cOpts.premultiplied = C.int(boolToInt(*opts.Premultiplied)) - } - } - - ret := C.gen_vips_smartcrop(input, C.int(width), C.int(height), &out_attentionX, &out_out, &out_attentionY, &cOpts) - if ret != 0 { - return 0, nil, 0, handleImageError(out_out) - } - - return int(out_attentionX), out_out, int(out_attentionY), nil -} - -// vipsGenSobel calls the vips sobel operation. -// Sobel edge detector -func vipsGenSobel(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("sobel") - - var out_out *C.VipsImage - - ret := C.gen_vips_sobel(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSpcor calls the vips spcor operation. -// spatial correlation -func vipsGenSpcor(input *C.VipsImage, ref *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("spcor") - - var out_out *C.VipsImage - - ret := C.gen_vips_spcor(input, ref, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSpectrum calls the vips spectrum operation. -// make displayable power spectrum -func vipsGenSpectrum(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("spectrum") - - var out_out *C.VipsImage - - ret := C.gen_vips_spectrum(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenStats calls the vips stats operation. -// find many image stats -func vipsGenStats(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("stats") - - var out_out *C.VipsImage - - ret := C.gen_vips_stats(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// StdifOptions are optional parameters for stdif. -type StdifOptions struct { - S0 *float64 - B *float64 - M0 *float64 - A *float64 -} - -// vipsGenStdif calls the vips stdif operation. -// statistical difference -func vipsGenStdif(input *C.VipsImage, width int, height int, opts *StdifOptions) (*C.VipsImage, error) { - incOpCounter("stdif") - - var out_out *C.VipsImage - - var cOpts C.GenStdifOpts - if opts != nil { - if opts.S0 != nil { - cOpts.has_s0 = 1 - cOpts.s0 = C.double(*opts.S0) - } - if opts.B != nil { - cOpts.has_b = 1 - cOpts.b = C.double(*opts.B) - } - if opts.M0 != nil { - cOpts.has_m0 = 1 - cOpts.m0 = C.double(*opts.M0) - } - if opts.A != nil { - cOpts.has_a = 1 - cOpts.a = C.double(*opts.A) - } - } - - ret := C.gen_vips_stdif(input, C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// SubsampleOptions are optional parameters for subsample. -type SubsampleOptions struct { - Point *bool -} - -// vipsGenSubsample calls the vips subsample operation. -// subsample an image -func vipsGenSubsample(input *C.VipsImage, xfac int, yfac int, opts *SubsampleOptions) (*C.VipsImage, error) { - incOpCounter("subsample") - - var out_out *C.VipsImage - - var cOpts C.GenSubsampleOpts - if opts != nil { - if opts.Point != nil { - cOpts.has_point = 1 - cOpts.point = C.int(boolToInt(*opts.Point)) - } - } - - ret := C.gen_vips_subsample(input, C.int(xfac), C.int(yfac), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSubtract calls the vips subtract operation. -// subtract two images -func vipsGenSubtract(left *C.VipsImage, right *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("subtract") - - var out_out *C.VipsImage - - ret := C.gen_vips_subtract(left, right, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenSum calls the vips sum operation. -// sum an array of images -func vipsGenSum(input []*C.VipsImage) (*C.VipsImage, error) { - incOpCounter("sum") - - var out_out *C.VipsImage - - ret := C.gen_vips_sum((**C.VipsImage)(unsafe.Pointer(&input[0])), C.int(len(input)), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// TilecacheOptions are optional parameters for tilecache. -type TilecacheOptions struct { - TileWidth *int - TileHeight *int - MaxTiles *int - Access *int - Threaded *bool - Persistent *bool -} - -// vipsGenTilecache calls the vips tilecache operation. -// cache an image as a set of tiles -func vipsGenTilecache(input *C.VipsImage, opts *TilecacheOptions) (*C.VipsImage, error) { - incOpCounter("tilecache") - - var out_out *C.VipsImage - - var cOpts C.GenTilecacheOpts - if opts != nil { - if opts.TileWidth != nil { - cOpts.has_tileWidth = 1 - cOpts.tileWidth = C.int(*opts.TileWidth) - } - if opts.TileHeight != nil { - cOpts.has_tileHeight = 1 - cOpts.tileHeight = C.int(*opts.TileHeight) - } - if opts.MaxTiles != nil { - cOpts.has_maxTiles = 1 - cOpts.maxTiles = C.int(*opts.MaxTiles) - } - if opts.Access != nil { - cOpts.has_access = 1 - cOpts.access = C.VipsAccess(*opts.Access) - } - if opts.Threaded != nil { - cOpts.has_threaded = 1 - cOpts.threaded = C.int(boolToInt(*opts.Threaded)) - } - if opts.Persistent != nil { - cOpts.has_persistent = 1 - cOpts.persistent = C.int(boolToInt(*opts.Persistent)) - } - } - - ret := C.gen_vips_tilecache(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// TonelutOptions are optional parameters for tonelut. -type TonelutOptions struct { - InMax *int - OutMax *int - Lb *float64 - Lw *float64 - Ps *float64 - Pm *float64 - Ph *float64 - S *float64 - M *float64 - H *float64 -} - -// vipsGenTonelut calls the vips tonelut operation. -// build a look-up table -func vipsGenTonelut(opts *TonelutOptions) (*C.VipsImage, error) { - incOpCounter("tonelut") - - var out_out *C.VipsImage - - var cOpts C.GenTonelutOpts - if opts != nil { - if opts.InMax != nil { - cOpts.has_inMax = 1 - cOpts.inMax = C.int(*opts.InMax) - } - if opts.OutMax != nil { - cOpts.has_outMax = 1 - cOpts.outMax = C.int(*opts.OutMax) - } - if opts.Lb != nil { - cOpts.has_Lb = 1 - cOpts.Lb = C.double(*opts.Lb) - } - if opts.Lw != nil { - cOpts.has_Lw = 1 - cOpts.Lw = C.double(*opts.Lw) - } - if opts.Ps != nil { - cOpts.has_Ps = 1 - cOpts.Ps = C.double(*opts.Ps) - } - if opts.Pm != nil { - cOpts.has_Pm = 1 - cOpts.Pm = C.double(*opts.Pm) - } - if opts.Ph != nil { - cOpts.has_Ph = 1 - cOpts.Ph = C.double(*opts.Ph) - } - if opts.S != nil { - cOpts.has_S = 1 - cOpts.S = C.double(*opts.S) - } - if opts.M != nil { - cOpts.has_M = 1 - cOpts.M = C.double(*opts.M) - } - if opts.H != nil { - cOpts.has_H = 1 - cOpts.H = C.double(*opts.H) - } - } - - ret := C.gen_vips_tonelut(&out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// Transpose3dOptions are optional parameters for transpose3d. -type Transpose3dOptions struct { - PageHeight *int -} - -// vipsGenTranspose3d calls the vips transpose3d operation. -// transpose3d an image -func vipsGenTranspose3d(input *C.VipsImage, opts *Transpose3dOptions) (*C.VipsImage, error) { - incOpCounter("transpose3d") - - var out_out *C.VipsImage - - var cOpts C.GenTranspose3dOpts - if opts != nil { - if opts.PageHeight != nil { - cOpts.has_pageHeight = 1 - cOpts.pageHeight = C.int(*opts.PageHeight) - } - } - - ret := C.gen_vips_transpose3d(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenUhdr2scRGB calls the vips uhdr2scRGB operation. -// transform uhdr to scRGB -func vipsGenUhdr2scRGB(input *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("uhdr2scRGB") - - var out_out *C.VipsImage - - ret := C.gen_vips_uhdr2scRGB(input, &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// UnpremultiplyOptions are optional parameters for unpremultiply. -type UnpremultiplyOptions struct { - MaxAlpha *float64 - AlphaBand *int -} - -// vipsGenUnpremultiply calls the vips unpremultiply operation. -// unpremultiply image alpha -func vipsGenUnpremultiply(input *C.VipsImage, opts *UnpremultiplyOptions) (*C.VipsImage, error) { - incOpCounter("unpremultiply") - - var out_out *C.VipsImage - - var cOpts C.GenUnpremultiplyOpts - if opts != nil { - if opts.MaxAlpha != nil { - cOpts.has_maxAlpha = 1 - cOpts.maxAlpha = C.double(*opts.MaxAlpha) - } - if opts.AlphaBand != nil { - cOpts.has_alphaBand = 1 - cOpts.alphaBand = C.int(*opts.AlphaBand) - } - } - - ret := C.gen_vips_unpremultiply(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// WorleyOptions are optional parameters for worley. -type WorleyOptions struct { - CellSize *int - Seed *int -} - -// vipsGenWorley calls the vips worley operation. -// make a worley noise image -func vipsGenWorley(width int, height int, opts *WorleyOptions) (*C.VipsImage, error) { - incOpCounter("worley") - - var out_out *C.VipsImage - - var cOpts C.GenWorleyOpts - if opts != nil { - if opts.CellSize != nil { - cOpts.has_cellSize = 1 - cOpts.cellSize = C.int(*opts.CellSize) - } - if opts.Seed != nil { - cOpts.has_seed = 1 - cOpts.seed = C.int(*opts.Seed) - } - } - - ret := C.gen_vips_worley(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// WrapOptions are optional parameters for wrap. -type WrapOptions struct { - X *int - Y *int -} - -// vipsGenWrap calls the vips wrap operation. -// wrap image origin -func vipsGenWrap(input *C.VipsImage, opts *WrapOptions) (*C.VipsImage, error) { - incOpCounter("wrap") - - var out_out *C.VipsImage - - var cOpts C.GenWrapOpts - if opts != nil { - if opts.X != nil { - cOpts.has_x = 1 - cOpts.x = C.int(*opts.X) - } - if opts.Y != nil { - cOpts.has_y = 1 - cOpts.y = C.int(*opts.Y) - } - } - - ret := C.gen_vips_wrap(input, &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// XyzOptions are optional parameters for xyz. -type XyzOptions struct { - Csize *int - Dsize *int - Esize *int -} - -// vipsGenXyz calls the vips xyz operation. -// make an image where pixel values are coordinates -func vipsGenXyz(width int, height int, opts *XyzOptions) (*C.VipsImage, error) { - incOpCounter("xyz") - - var out_out *C.VipsImage - - var cOpts C.GenXyzOpts - if opts != nil { - if opts.Csize != nil { - cOpts.has_csize = 1 - cOpts.csize = C.int(*opts.Csize) - } - if opts.Dsize != nil { - cOpts.has_dsize = 1 - cOpts.dsize = C.int(*opts.Dsize) - } - if opts.Esize != nil { - cOpts.has_esize = 1 - cOpts.esize = C.int(*opts.Esize) - } - } - - ret := C.gen_vips_xyz(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// ZoneOptions are optional parameters for zone. -type ZoneOptions struct { - Uchar *bool -} - -// vipsGenZone calls the vips zone operation. -// make a zone plate -func vipsGenZone(width int, height int, opts *ZoneOptions) (*C.VipsImage, error) { - incOpCounter("zone") - - var out_out *C.VipsImage - - var cOpts C.GenZoneOpts - if opts != nil { - if opts.Uchar != nil { - cOpts.has_uchar = 1 - cOpts.uchar = C.int(boolToInt(*opts.Uchar)) - } - } - - ret := C.gen_vips_zone(C.int(width), C.int(height), &out_out, &cOpts) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - -// vipsGenZoom calls the vips zoom operation. -// zoom an image -func vipsGenZoom(input *C.VipsImage, xfac int, yfac int) (*C.VipsImage, error) { - incOpCounter("zoom") - - var out_out *C.VipsImage - - ret := C.gen_vips_zoom(input, C.int(xfac), C.int(yfac), &out_out) - if ret != 0 { - return nil, handleImageError(out_out) - } - - return out_out, nil -} - diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/generated.h b/vendor/github.com/davidbyttow/govips/v2/vips/generated.h deleted file mode 100644 index 930eccb5eb..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/generated.h +++ /dev/null @@ -1,1181 +0,0 @@ -// Code generated by vipsgen. DO NOT EDIT. -#ifndef GENERATED_H -#define GENERATED_H - -#include -#include - -int gen_vips_CMC2LCh(VipsImage * input, VipsImage ** out_out); - -int gen_vips_CMYK2XYZ(VipsImage * input, VipsImage ** out_out); - -int gen_vips_HSV2sRGB(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LCh2CMC(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LCh2Lab(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Lab2LCh(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Lab2LabQ(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Lab2LabS(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_temp; - double *temp; int temp_n; -} GenLab2XYZOpts; - -int gen_vips_Lab2XYZ(VipsImage * input, VipsImage ** out_out, GenLab2XYZOpts *opts); - -int gen_vips_LabQ2Lab(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LabQ2LabS(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LabQ2sRGB(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LabS2Lab(VipsImage * input, VipsImage ** out_out); - -int gen_vips_LabS2LabQ(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Oklab2Oklch(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Oklab2XYZ(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Oklch2Oklab(VipsImage * input, VipsImage ** out_out); - -int gen_vips_XYZ2CMYK(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_temp; - double *temp; int temp_n; -} GenXYZ2LabOpts; - -int gen_vips_XYZ2Lab(VipsImage * input, VipsImage ** out_out, GenXYZ2LabOpts *opts); - -int gen_vips_XYZ2Oklab(VipsImage * input, VipsImage ** out_out); - -int gen_vips_XYZ2Yxy(VipsImage * input, VipsImage ** out_out); - -int gen_vips_XYZ2scRGB(VipsImage * input, VipsImage ** out_out); - -int gen_vips_Yxy2XYZ(VipsImage * input, VipsImage ** out_out); - -int gen_vips_abs(VipsImage * input, VipsImage ** out_out); - -int gen_vips_add(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -typedef struct { - int has_interpolate; - VipsInterpolate *interpolate; - int has_oarea; - int *oarea; int oarea_n; - int has_odx; - double odx; - int has_ody; - double ody; - int has_idx; - double idx; - int has_idy; - double idy; - int has_background; - double *background; int background_n; - int has_premultiplied; - int premultiplied; - int has_extend; - VipsExtend extend; -} GenAffineOpts; - -int gen_vips_affine(VipsImage * input, double * matrix, int matrix_n, VipsImage ** out_out, GenAffineOpts *opts); - -typedef struct { - int has_across; - int across; - int has_shim; - int shim; - int has_background; - double *background; int background_n; - int has_halign; - VipsAlign halign; - int has_valign; - VipsAlign valign; - int has_hspacing; - int hspacing; - int has_vspacing; - int vspacing; -} GenArrayjoinOpts; - -int gen_vips_arrayjoin(VipsImage **input, int input_n, VipsImage ** out_out, GenArrayjoinOpts *opts); - -int gen_vips_autorot(VipsImage * input, VipsImage ** out_out, int * out_angle, int * out_flip); - -int gen_vips_avg(VipsImage * input, double * out_out); - -int gen_vips_bandbool(VipsImage * input, VipsOperationBoolean boolean, VipsImage ** out_out); - -typedef struct { - int has_factor; - int factor; -} GenBandfoldOpts; - -int gen_vips_bandfold(VipsImage * input, VipsImage ** out_out, GenBandfoldOpts *opts); - -int gen_vips_bandjoin(VipsImage **input, int input_n, VipsImage ** out_out); - -int gen_vips_bandjoin_const(VipsImage * input, double * c, int c_n, VipsImage ** out_out); - -int gen_vips_bandmean(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_index; - int index; -} GenBandrankOpts; - -int gen_vips_bandrank(VipsImage **input, int input_n, VipsImage ** out_out, GenBandrankOpts *opts); - -typedef struct { - int has_factor; - int factor; -} GenBandunfoldOpts; - -int gen_vips_bandunfold(VipsImage * input, VipsImage ** out_out, GenBandunfoldOpts *opts); - -typedef struct { - int has_bands; - int bands; -} GenBlackOpts; - -int gen_vips_black(int width, int height, VipsImage ** out_out, GenBlackOpts *opts); - -int gen_vips_boolean(VipsImage * left, VipsImage * right, VipsOperationBoolean boolean, VipsImage ** out_out); - -int gen_vips_boolean_const(VipsImage * input, VipsOperationBoolean boolean, double * c, int c_n, VipsImage ** out_out); - -int gen_vips_buildlut(VipsImage * input, VipsImage ** out_out); - -int gen_vips_byteswap(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_maxTiles; - int maxTiles; - int has_tileHeight; - int tileHeight; - int has_tileWidth; - int tileWidth; -} GenCacheOpts; - -int gen_vips_cache(VipsImage * input, VipsImage ** out_out, GenCacheOpts *opts); - -typedef struct { - int has_sigma; - double sigma; - int has_precision; - VipsPrecision precision; -} GenCannyOpts; - -int gen_vips_canny(VipsImage * input, VipsImage ** out_out, GenCannyOpts *opts); - -typedef struct { - int has_shift; - int shift; -} GenCastOpts; - -int gen_vips_cast(VipsImage * input, VipsBandFormat format, VipsImage ** out_out, GenCastOpts *opts); - -typedef struct { - int has_min; - double min; - int has_max; - double max; -} GenClampOpts; - -int gen_vips_clamp(VipsImage * input, VipsImage ** out_out, GenClampOpts *opts); - -typedef struct { - int has_times; - int times; - int has_angle; - VipsAngle45 angle; - int has_combine; - VipsCombine combine; - int has_precision; - VipsPrecision precision; - int has_layers; - int layers; - int has_cluster; - int cluster; -} GenCompassOpts; - -int gen_vips_compass(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenCompassOpts *opts); - -int gen_vips_complex(VipsImage * input, VipsOperationComplex cmplx, VipsImage ** out_out); - -int gen_vips_complex2(VipsImage * left, VipsImage * right, VipsOperationComplex2 cmplx, VipsImage ** out_out); - -int gen_vips_complexform(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_complexget(VipsImage * input, VipsOperationComplexget get, VipsImage ** out_out); - -typedef struct { - int has_x; - int x; - int has_y; - int y; - int has_compositingSpace; - VipsInterpretation compositingSpace; - int has_premultiplied; - int premultiplied; -} GenComposite2Opts; - -int gen_vips_composite2(VipsImage * base, VipsImage * overlay, VipsBlendMode mode, VipsImage ** out_out, GenComposite2Opts *opts); - -typedef struct { - int has_precision; - VipsPrecision precision; - int has_layers; - int layers; - int has_cluster; - int cluster; -} GenConvOpts; - -int gen_vips_conv(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvOpts *opts); - -typedef struct { - int has_layers; - int layers; - int has_cluster; - int cluster; -} GenConvaOpts; - -int gen_vips_conva(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvaOpts *opts); - -typedef struct { - int has_layers; - int layers; -} GenConvasepOpts; - -int gen_vips_convasep(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvasepOpts *opts); - -int gen_vips_convf(VipsImage * input, VipsImage * mask, VipsImage ** out_out); - -int gen_vips_convi(VipsImage * input, VipsImage * mask, VipsImage ** out_out); - -typedef struct { - int has_precision; - VipsPrecision precision; - int has_layers; - int layers; - int has_cluster; - int cluster; -} GenConvsepOpts; - -int gen_vips_convsep(VipsImage * input, VipsImage * mask, VipsImage ** out_out, GenConvsepOpts *opts); - -typedef struct { - int has_width; - int width; - int has_height; - int height; - int has_bands; - int bands; - int has_format; - VipsBandFormat format; - int has_coding; - VipsCoding coding; - int has_interpretation; - VipsInterpretation interpretation; - int has_xres; - double xres; - int has_yres; - double yres; - int has_xoffset; - int xoffset; - int has_yoffset; - int yoffset; -} GenCopyOpts; - -int gen_vips_copy(VipsImage * input, VipsImage ** out_out, GenCopyOpts *opts); - -int gen_vips_countlines(VipsImage * input, VipsDirection direction, double * out_nolines); - -int gen_vips_dE00(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_dE76(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_dECMC(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_deviate(VipsImage * input, double * out_out); - -int gen_vips_divide(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_extract_area(VipsImage * input, int left, int top, int width, int height, VipsImage ** out_out); - -typedef struct { - int has_n; - int n; -} GenExtractBandOpts; - -int gen_vips_extract_band(VipsImage * input, int band, VipsImage ** out_out, GenExtractBandOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_factor; - double factor; -} GenEyeOpts; - -int gen_vips_eye(int width, int height, VipsImage ** out_out, GenEyeOpts *opts); - -int gen_vips_falsecolour(VipsImage * input, VipsImage ** out_out); - -int gen_vips_fastcor(VipsImage * input, VipsImage * ref, VipsImage ** out_out); - -int gen_vips_fill_nearest(VipsImage * input, VipsImage ** out_out, VipsImage ** out_distance); - -typedef struct { - int has_background; - double *background; int background_n; - int has_maxAlpha; - double maxAlpha; -} GenFlattenOpts; - -int gen_vips_flatten(VipsImage * input, VipsImage ** out_out, GenFlattenOpts *opts); - -int gen_vips_flip(VipsImage * input, VipsDirection direction, VipsImage ** out_out); - -int gen_vips_float2rad(VipsImage * input, VipsImage ** out_out); - -int gen_vips_fractsurf(int width, int height, double fractalDimension, VipsImage ** out_out); - -int gen_vips_freqmult(VipsImage * input, VipsImage * mask, VipsImage ** out_out); - -int gen_vips_fwfft(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_exponent; - double exponent; -} GenGammaOpts; - -int gen_vips_gamma(VipsImage * input, VipsImage ** out_out, GenGammaOpts *opts); - -typedef struct { - int has_minAmpl; - double minAmpl; - int has_precision; - VipsPrecision precision; -} GenGaussblurOpts; - -int gen_vips_gaussblur(VipsImage * input, double sigma, VipsImage ** out_out, GenGaussblurOpts *opts); - -typedef struct { - int has_separable; - int separable; - int has_precision; - VipsPrecision precision; -} GenGaussmatOpts; - -int gen_vips_gaussmat(double sigma, double minAmpl, VipsImage ** out_out, GenGaussmatOpts *opts); - -typedef struct { - int has_sigma; - double sigma; - int has_mean; - double mean; - int has_seed; - int seed; -} GenGaussnoiseOpts; - -int gen_vips_gaussnoise(int width, int height, VipsImage ** out_out, GenGaussnoiseOpts *opts); - -typedef struct { - int has_gamma; - double gamma; - int has_intOutput; - int intOutput; -} GenGlobalbalanceOpts; - -int gen_vips_globalbalance(VipsImage * input, VipsImage ** out_out, GenGlobalbalanceOpts *opts); - -typedef struct { - int has_extend; - VipsExtend extend; - int has_background; - double *background; int background_n; -} GenGravityOpts; - -int gen_vips_gravity(VipsImage * input, VipsCompassDirection direction, int width, int height, VipsImage ** out_out, GenGravityOpts *opts); - -typedef struct { - int has_uchar; - int uchar; -} GenGreyOpts; - -int gen_vips_grey(int width, int height, VipsImage ** out_out, GenGreyOpts *opts); - -int gen_vips_grid(VipsImage * input, int tileHeight, int across, int down, VipsImage ** out_out); - -int gen_vips_hist_cum(VipsImage * input, VipsImage ** out_out); - -int gen_vips_hist_entropy(VipsImage * input, double * out_out); - -typedef struct { - int has_band; - int band; -} GenHistEqualOpts; - -int gen_vips_hist_equal(VipsImage * input, VipsImage ** out_out, GenHistEqualOpts *opts); - -typedef struct { - int has_band; - int band; -} GenHistFindOpts; - -int gen_vips_hist_find(VipsImage * input, VipsImage ** out_out, GenHistFindOpts *opts); - -typedef struct { - int has_combine; - VipsCombine combine; -} GenHistFindIndexedOpts; - -int gen_vips_hist_find_indexed(VipsImage * input, VipsImage * index, VipsImage ** out_out, GenHistFindIndexedOpts *opts); - -typedef struct { - int has_bins; - int bins; -} GenHistFindNdimOpts; - -int gen_vips_hist_find_ndim(VipsImage * input, VipsImage ** out_out, GenHistFindNdimOpts *opts); - -int gen_vips_hist_ismonotonic(VipsImage * input, int * out_monotonic); - -typedef struct { - int has_maxSlope; - int maxSlope; -} GenHistLocalOpts; - -int gen_vips_hist_local(VipsImage * input, int width, int height, VipsImage ** out_out, GenHistLocalOpts *opts); - -int gen_vips_hist_match(VipsImage * input, VipsImage * ref, VipsImage ** out_out); - -int gen_vips_hist_norm(VipsImage * input, VipsImage ** out_out); - -int gen_vips_hist_plot(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_scale; - int scale; - int has_minRadius; - int minRadius; - int has_maxRadius; - int maxRadius; -} GenHoughCircleOpts; - -int gen_vips_hough_circle(VipsImage * input, VipsImage ** out_out, GenHoughCircleOpts *opts); - -typedef struct { - int has_width; - int width; - int has_height; - int height; -} GenHoughLineOpts; - -int gen_vips_hough_line(VipsImage * input, VipsImage ** out_out, GenHoughLineOpts *opts); - -typedef struct { - int has_pcs; - VipsPCS pcs; - int has_intent; - VipsIntent intent; - int has_blackPointCompensation; - int blackPointCompensation; - int has_outputProfile; - const char *outputProfile; - int has_depth; - int depth; -} GenIccExportOpts; - -int gen_vips_icc_export(VipsImage * input, VipsImage ** out_out, GenIccExportOpts *opts); - -typedef struct { - int has_pcs; - VipsPCS pcs; - int has_intent; - VipsIntent intent; - int has_blackPointCompensation; - int blackPointCompensation; - int has_embedded; - int embedded; - int has_inputProfile; - const char *inputProfile; -} GenIccImportOpts; - -int gen_vips_icc_import(VipsImage * input, VipsImage ** out_out, GenIccImportOpts *opts); - -typedef struct { - int has_bands; - int bands; - int has_ushort; - int ushort; - int has_size; - int size; -} GenIdentityOpts; - -int gen_vips_identity(VipsImage ** out_out, GenIdentityOpts *opts); - -typedef struct { - int has_blend; - int blend; -} GenIfthenelseOpts; - -int gen_vips_ifthenelse(VipsImage * cond, VipsImage * in1, VipsImage * in2, VipsImage ** out_out, GenIfthenelseOpts *opts); - -typedef struct { - int has_expand; - int expand; - int has_background; - double *background; int background_n; -} GenInsertOpts; - -int gen_vips_insert(VipsImage * main, VipsImage * sub, int x, int y, VipsImage ** out_out, GenInsertOpts *opts); - -int gen_vips_invert(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_size; - int size; -} GenInvertlutOpts; - -int gen_vips_invertlut(VipsImage * input, VipsImage ** out_out, GenInvertlutOpts *opts); - -typedef struct { - int has_real; - int real; -} GenInvfftOpts; - -int gen_vips_invfft(VipsImage * input, VipsImage ** out_out, GenInvfftOpts *opts); - -typedef struct { - int has_expand; - int expand; - int has_shim; - int shim; - int has_background; - double *background; int background_n; - int has_align; - VipsAlign align; -} GenJoinOpts; - -int gen_vips_join(VipsImage * in1, VipsImage * in2, VipsDirection direction, VipsImage ** out_out, GenJoinOpts *opts); - -int gen_vips_labelregions(VipsImage * input, VipsImage ** out_mask, int * out_segments); - -typedef struct { - int has_uchar; - int uchar; -} GenLinearOpts; - -int gen_vips_linear(VipsImage * input, double * a, int a_n, double * b, int b_n, VipsImage ** out_out, GenLinearOpts *opts); - -typedef struct { - int has_tileHeight; - int tileHeight; - int has_access; - VipsAccess access; - int has_threaded; - int threaded; - int has_persistent; - int persistent; -} GenLinecacheOpts; - -int gen_vips_linecache(VipsImage * input, VipsImage ** out_out, GenLinecacheOpts *opts); - -typedef struct { - int has_separable; - int separable; - int has_precision; - VipsPrecision precision; -} GenLogmatOpts; - -int gen_vips_logmat(double sigma, double minAmpl, VipsImage ** out_out, GenLogmatOpts *opts); - -typedef struct { - int has_interpolate; - VipsInterpolate *interpolate; - int has_background; - double *background; int background_n; - int has_premultiplied; - int premultiplied; - int has_extend; - VipsExtend extend; -} GenMapimOpts; - -int gen_vips_mapim(VipsImage * input, VipsImage * index, VipsImage ** out_out, GenMapimOpts *opts); - -typedef struct { - int has_band; - int band; -} GenMaplutOpts; - -int gen_vips_maplut(VipsImage * input, VipsImage * lut, VipsImage ** out_out, GenMaplutOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskButterworthOpts; - -int gen_vips_mask_butterworth(int width, int height, double order, double frequencyCutoff, double amplitudeCutoff, VipsImage ** out_out, GenMaskButterworthOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskButterworthBandOpts; - -int gen_vips_mask_butterworth_band(int width, int height, double order, double frequencyCutoffX, double frequencyCutoffY, double radius, double amplitudeCutoff, VipsImage ** out_out, GenMaskButterworthBandOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskButterworthRingOpts; - -int gen_vips_mask_butterworth_ring(int width, int height, double order, double frequencyCutoff, double amplitudeCutoff, double ringwidth, VipsImage ** out_out, GenMaskButterworthRingOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskFractalOpts; - -int gen_vips_mask_fractal(int width, int height, double fractalDimension, VipsImage ** out_out, GenMaskFractalOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskGaussianOpts; - -int gen_vips_mask_gaussian(int width, int height, double frequencyCutoff, double amplitudeCutoff, VipsImage ** out_out, GenMaskGaussianOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskGaussianBandOpts; - -int gen_vips_mask_gaussian_band(int width, int height, double frequencyCutoffX, double frequencyCutoffY, double radius, double amplitudeCutoff, VipsImage ** out_out, GenMaskGaussianBandOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskGaussianRingOpts; - -int gen_vips_mask_gaussian_ring(int width, int height, double frequencyCutoff, double amplitudeCutoff, double ringwidth, VipsImage ** out_out, GenMaskGaussianRingOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskIdealOpts; - -int gen_vips_mask_ideal(int width, int height, double frequencyCutoff, VipsImage ** out_out, GenMaskIdealOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskIdealBandOpts; - -int gen_vips_mask_ideal_band(int width, int height, double frequencyCutoffX, double frequencyCutoffY, double radius, VipsImage ** out_out, GenMaskIdealBandOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_nodc; - int nodc; - int has_reject; - int reject; - int has_optical; - int optical; -} GenMaskIdealRingOpts; - -int gen_vips_mask_ideal_ring(int width, int height, double frequencyCutoff, double ringwidth, VipsImage ** out_out, GenMaskIdealRingOpts *opts); - -typedef struct { - int has_hwindow; - int hwindow; - int has_harea; - int harea; - int has_search; - int search; - int has_interpolate; - VipsInterpolate *interpolate; -} GenMatchOpts; - -int gen_vips_match(VipsImage * ref, VipsImage * sec, int xr1, int yr1, int xs1, int ys1, int xr2, int yr2, int xs2, int ys2, VipsImage ** out_out, GenMatchOpts *opts); - -int gen_vips_math(VipsImage * input, VipsOperationMath math, VipsImage ** out_out); - -int gen_vips_math2(VipsImage * left, VipsImage * right, VipsOperationMath2 math2, VipsImage ** out_out); - -int gen_vips_math2_const(VipsImage * input, VipsOperationMath2 math2, double * c, int c_n, VipsImage ** out_out); - -int gen_vips_matrixinvert(VipsImage * input, VipsImage ** out_out); - -int gen_vips_matrixmultiply(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_maxpair(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -typedef struct { - int has_mblend; - int mblend; -} GenMergeOpts; - -int gen_vips_merge(VipsImage * ref, VipsImage * sec, VipsDirection direction, int dx, int dy, VipsImage ** out_out, GenMergeOpts *opts); - -int gen_vips_minpair(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_morph(VipsImage * input, VipsImage * mask, VipsOperationMorphology morph, VipsImage ** out_out); - -typedef struct { - int has_hwindow; - int hwindow; - int has_harea; - int harea; - int has_mblend; - int mblend; - int has_bandno; - int bandno; -} GenMosaicOpts; - -int gen_vips_mosaic(VipsImage * ref, VipsImage * sec, VipsDirection direction, int xref, int yref, int xsec, int ysec, VipsImage ** out_out, int * out_dx0, int * out_dy0, double * out_scale1, double * out_angle1, double * out_dy1, double * out_dx1, GenMosaicOpts *opts); - -typedef struct { - int has_hwindow; - int hwindow; - int has_harea; - int harea; - int has_search; - int search; - int has_interpolate; - VipsInterpolate *interpolate; - int has_mblend; - int mblend; -} GenMosaic1Opts; - -int gen_vips_mosaic1(VipsImage * ref, VipsImage * sec, VipsDirection direction, int xr1, int yr1, int xs1, int ys1, int xr2, int yr2, int xs2, int ys2, VipsImage ** out_out, GenMosaic1Opts *opts); - -typedef struct { - int has_band; - int band; -} GenMsbOpts; - -int gen_vips_msb(VipsImage * input, VipsImage ** out_out, GenMsbOpts *opts); - -int gen_vips_multiply(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_percent(VipsImage * input, double percent, int * out_threshold); - -typedef struct { - int has_cellSize; - int cellSize; - int has_uchar; - int uchar; - int has_seed; - int seed; -} GenPerlinOpts; - -int gen_vips_perlin(int width, int height, VipsImage ** out_out, GenPerlinOpts *opts); - -int gen_vips_phasecor(VipsImage * input, VipsImage * in2, VipsImage ** out_out); - -typedef struct { - int has_maxAlpha; - double maxAlpha; -} GenPremultiplyOpts; - -int gen_vips_premultiply(VipsImage * input, VipsImage ** out_out, GenPremultiplyOpts *opts); - -int gen_vips_prewitt(VipsImage * input, VipsImage ** out_out); - -int gen_vips_profile(VipsImage * input, VipsImage ** out_columns, VipsImage ** out_rows); - -int gen_vips_project(VipsImage * input, VipsImage ** out_columns, VipsImage ** out_rows); - -typedef struct { - int has_interpolate; - VipsInterpolate *interpolate; -} GenQuadraticOpts; - -int gen_vips_quadratic(VipsImage * input, VipsImage * coeff, VipsImage ** out_out, GenQuadraticOpts *opts); - -int gen_vips_rad2float(VipsImage * input, VipsImage ** out_out); - -int gen_vips_rank(VipsImage * input, int width, int height, int index, VipsImage ** out_out); - -int gen_vips_recomb(VipsImage * input, VipsImage * m, VipsImage ** out_out); - -typedef struct { - int has_kernel; - VipsKernel kernel; - int has_gap; - double gap; -} GenReduceOpts; - -int gen_vips_reduce(VipsImage * input, double hshrink, double vshrink, VipsImage ** out_out, GenReduceOpts *opts); - -typedef struct { - int has_kernel; - VipsKernel kernel; - int has_gap; - double gap; -} GenReducehOpts; - -int gen_vips_reduceh(VipsImage * input, double hshrink, VipsImage ** out_out, GenReducehOpts *opts); - -typedef struct { - int has_kernel; - VipsKernel kernel; - int has_gap; - double gap; -} GenReducevOpts; - -int gen_vips_reducev(VipsImage * input, double vshrink, VipsImage ** out_out, GenReducevOpts *opts); - -int gen_vips_relational(VipsImage * left, VipsImage * right, VipsOperationRelational relational, VipsImage ** out_out); - -int gen_vips_relational_const(VipsImage * input, VipsOperationRelational relational, double * c, int c_n, VipsImage ** out_out); - -int gen_vips_remainder(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_remainder_const(VipsImage * input, double * c, int c_n, VipsImage ** out_out); - -int gen_vips_remosaic(VipsImage * input, const char * oldStr, const char * newStr, VipsImage ** out_out); - -int gen_vips_replicate(VipsImage * input, int across, int down, VipsImage ** out_out); - -int gen_vips_rot(VipsImage * input, VipsAngle angle, VipsImage ** out_out); - -typedef struct { - int has_angle; - VipsAngle45 angle; -} GenRot45Opts; - -int gen_vips_rot45(VipsImage * input, VipsImage ** out_out, GenRot45Opts *opts); - -typedef struct { - int has_interpolate; - VipsInterpolate *interpolate; - int has_background; - double *background; int background_n; - int has_odx; - double odx; - int has_ody; - double ody; - int has_idx; - double idx; - int has_idy; - double idy; -} GenRotateOpts; - -int gen_vips_rotate(VipsImage * input, double angle, VipsImage ** out_out, GenRotateOpts *opts); - -int gen_vips_round(VipsImage * input, VipsOperationRound round, VipsImage ** out_out); - -int gen_vips_sRGB2HSV(VipsImage * input, VipsImage ** out_out); - -int gen_vips_sRGB2scRGB(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_depth; - int depth; -} GenScRGB2BWOpts; - -int gen_vips_scRGB2BW(VipsImage * input, VipsImage ** out_out, GenScRGB2BWOpts *opts); - -int gen_vips_scRGB2XYZ(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_depth; - int depth; -} GenScRGB2sRGBOpts; - -int gen_vips_scRGB2sRGB(VipsImage * input, VipsImage ** out_out, GenScRGB2sRGBOpts *opts); - -typedef struct { - int has_exp; - double exp; - int has_log; - int log; -} GenScaleOpts; - -int gen_vips_scale(VipsImage * input, VipsImage ** out_out, GenScaleOpts *opts); - -int gen_vips_scharr(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_tileHeight; - int tileHeight; -} GenSequentialOpts; - -int gen_vips_sequential(VipsImage * input, VipsImage ** out_out, GenSequentialOpts *opts); - -typedef struct { - int has_sigma; - double sigma; - int has_x1; - double x1; - int has_y2; - double y2; - int has_y3; - double y3; - int has_m1; - double m1; - int has_m2; - double m2; -} GenSharpenOpts; - -int gen_vips_sharpen(VipsImage * input, VipsImage ** out_out, GenSharpenOpts *opts); - -typedef struct { - int has_ceil; - int ceil; -} GenShrinkOpts; - -int gen_vips_shrink(VipsImage * input, double hshrink, double vshrink, VipsImage ** out_out, GenShrinkOpts *opts); - -typedef struct { - int has_ceil; - int ceil; -} GenShrinkhOpts; - -int gen_vips_shrinkh(VipsImage * input, int hshrink, VipsImage ** out_out, GenShrinkhOpts *opts); - -typedef struct { - int has_ceil; - int ceil; -} GenShrinkvOpts; - -int gen_vips_shrinkv(VipsImage * input, int vshrink, VipsImage ** out_out, GenShrinkvOpts *opts); - -int gen_vips_sign(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_scale; - double scale; - int has_angle; - double angle; - int has_interpolate; - VipsInterpolate *interpolate; - int has_background; - double *background; int background_n; - int has_odx; - double odx; - int has_ody; - double ody; - int has_idx; - double idx; - int has_idy; - double idy; -} GenSimilarityOpts; - -int gen_vips_similarity(VipsImage * input, VipsImage ** out_out, GenSimilarityOpts *opts); - -typedef struct { - int has_uchar; - int uchar; - int has_hfreq; - double hfreq; - int has_vfreq; - double vfreq; -} GenSinesOpts; - -int gen_vips_sines(int width, int height, VipsImage ** out_out, GenSinesOpts *opts); - -typedef struct { - int has_interesting; - VipsInteresting interesting; - int has_premultiplied; - int premultiplied; -} GenSmartcropOpts; - -int gen_vips_smartcrop(VipsImage * input, int width, int height, int * out_attentionX, VipsImage ** out_out, int * out_attentionY, GenSmartcropOpts *opts); - -int gen_vips_sobel(VipsImage * input, VipsImage ** out_out); - -int gen_vips_spcor(VipsImage * input, VipsImage * ref, VipsImage ** out_out); - -int gen_vips_spectrum(VipsImage * input, VipsImage ** out_out); - -int gen_vips_stats(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_s0; - double s0; - int has_b; - double b; - int has_m0; - double m0; - int has_a; - double a; -} GenStdifOpts; - -int gen_vips_stdif(VipsImage * input, int width, int height, VipsImage ** out_out, GenStdifOpts *opts); - -typedef struct { - int has_point; - int point; -} GenSubsampleOpts; - -int gen_vips_subsample(VipsImage * input, int xfac, int yfac, VipsImage ** out_out, GenSubsampleOpts *opts); - -int gen_vips_subtract(VipsImage * left, VipsImage * right, VipsImage ** out_out); - -int gen_vips_sum(VipsImage **input, int input_n, VipsImage ** out_out); - -typedef struct { - int has_tileWidth; - int tileWidth; - int has_tileHeight; - int tileHeight; - int has_maxTiles; - int maxTiles; - int has_access; - VipsAccess access; - int has_threaded; - int threaded; - int has_persistent; - int persistent; -} GenTilecacheOpts; - -int gen_vips_tilecache(VipsImage * input, VipsImage ** out_out, GenTilecacheOpts *opts); - -typedef struct { - int has_inMax; - int inMax; - int has_outMax; - int outMax; - int has_Lb; - double Lb; - int has_Lw; - double Lw; - int has_Ps; - double Ps; - int has_Pm; - double Pm; - int has_Ph; - double Ph; - int has_S; - double S; - int has_M; - double M; - int has_H; - double H; -} GenTonelutOpts; - -int gen_vips_tonelut(VipsImage ** out_out, GenTonelutOpts *opts); - -typedef struct { - int has_pageHeight; - int pageHeight; -} GenTranspose3dOpts; - -int gen_vips_transpose3d(VipsImage * input, VipsImage ** out_out, GenTranspose3dOpts *opts); - -int gen_vips_uhdr2scRGB(VipsImage * input, VipsImage ** out_out); - -typedef struct { - int has_maxAlpha; - double maxAlpha; - int has_alphaBand; - int alphaBand; -} GenUnpremultiplyOpts; - -int gen_vips_unpremultiply(VipsImage * input, VipsImage ** out_out, GenUnpremultiplyOpts *opts); - -typedef struct { - int has_cellSize; - int cellSize; - int has_seed; - int seed; -} GenWorleyOpts; - -int gen_vips_worley(int width, int height, VipsImage ** out_out, GenWorleyOpts *opts); - -typedef struct { - int has_x; - int x; - int has_y; - int y; -} GenWrapOpts; - -int gen_vips_wrap(VipsImage * input, VipsImage ** out_out, GenWrapOpts *opts); - -typedef struct { - int has_csize; - int csize; - int has_dsize; - int dsize; - int has_esize; - int esize; -} GenXyzOpts; - -int gen_vips_xyz(int width, int height, VipsImage ** out_out, GenXyzOpts *opts); - -typedef struct { - int has_uchar; - int uchar; -} GenZoneOpts; - -int gen_vips_zone(int width, int height, VipsImage ** out_out, GenZoneOpts *opts); - -int gen_vips_zoom(VipsImage * input, int xfac, int yfac, VipsImage ** out_out); - -#endif diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/govips.c b/vendor/github.com/davidbyttow/govips/v2/vips/govips.c deleted file mode 100644 index 0b220b9ece..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/govips.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "govips.h" - -static void govips_logging_handler(const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *message, gpointer user_data) { - govipsLoggingHandler((char *)log_domain, (int)log_level, (char *)message); -} - -static void null_logging_handler(const gchar *log_domain, - GLogLevelFlags log_level, const gchar *message, - gpointer user_data) {} - -void vips_set_logging_handler(void) { - g_log_set_default_handler(govips_logging_handler, NULL); -} - -void vips_unset_logging_handler(void) { - g_log_set_default_handler(null_logging_handler, NULL); -} - -/* This function skips the Govips logging handler and logs - directly to stdout. To be used only for testing and debugging. - Needed for CI because of a Go macOS bug which doesn't clean cgo callbacks on - exit. */ -void vips_default_logging_handler(void) { - g_log_set_default_handler(g_log_default_handler, NULL); -} \ No newline at end of file diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/govips.go b/vendor/github.com/davidbyttow/govips/v2/vips/govips.go deleted file mode 100644 index 7a8409ddfb..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/govips.go +++ /dev/null @@ -1,299 +0,0 @@ -// Package vips provides go bindings for libvips, a fast image processing library. -package vips - -// #cgo pkg-config: vips -// #include -// #include "govips.h" -import "C" -import ( - "errors" - "fmt" - "os" - "runtime" - "strings" - "sync" - "sync/atomic" - "testing" -) - -const ( - defaultConcurrencyLevel = 1 - defaultMaxCacheMem = 50 * 1024 * 1024 - defaultMaxCacheSize = 100 - defaultMaxCacheFiles = 0 -) - -var ( - // Version is the full libvips version string (x.y.z) - Version = C.GoString(C.vips_version_string()) - - // MajorVersion is the libvips major component of the version string (x in x.y.z) - MajorVersion = int(C.vips_version(0)) - - // MinorVersion is the libvips minor component of the version string (y in x.y.z) - MinorVersion = int(C.vips_version(1)) - - // MicroVersion is the libvips micro component of the version string (z in x.y.z) - // Also known as patch version - MicroVersion = int(C.vips_version(2)) - - running = false - hasShutdown = false - initLock sync.Mutex - statCollectorDone chan struct{} - once sync.Once - typeLoaders = make(map[string]ImageType) - supportedImageTypes = make(map[ImageType]bool) -) - -// Config allows fine-tuning of libvips library -type Config struct { - ConcurrencyLevel int - MaxCacheFiles int - MaxCacheMem int - MaxCacheSize int - ReportLeaks bool - CacheTrace bool - CollectStats bool -} - -// Startup sets up the libvips support and ensures the versions are correct. Pass in nil for -// default configuration. -func Startup(config *Config) error { - if hasShutdown { - return errors.New("govips cannot be stopped and restarted") - } - - initLock.Lock() - defer initLock.Unlock() - - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if running { - govipsLog("govips", LogLevelInfo, "warning libvips already started") - return nil - } - - if MajorVersion < 8 { - return errors.New("govips requires libvips version 8.10+") - } - - if MajorVersion == 8 && MinorVersion < 10 { - return errors.New("govips requires libvips version 8.10+") - } - - cName := C.CString("govips") - defer freeCString(cName) - - // Initialize govips logging handler and verbosity filter to historical default - if !currentLoggingOverridden { - govipsLoggingSettings(nil, LogLevelInfo) - } - - // Override default glib logging handler to intercept logging messages - enableLogging() - - err := C.vips_init(cName) - if err != 0 { - return fmt.Errorf("failed to start vips code=%v", err) - } - - running = true - - if config != nil { - if config.CollectStats { - statCollectorDone = collectStats() - } - - C.vips_leak_set(toGboolean(config.ReportLeaks)) - - if config.ConcurrencyLevel >= 0 { - C.vips_concurrency_set(C.int(config.ConcurrencyLevel)) - } else { - C.vips_concurrency_set(defaultConcurrencyLevel) - } - - if config.MaxCacheFiles >= 0 { - C.vips_cache_set_max_files(C.int(config.MaxCacheFiles)) - } else { - C.vips_cache_set_max_files(defaultMaxCacheFiles) - } - - if config.MaxCacheMem >= 0 { - C.vips_cache_set_max_mem(C.size_t(config.MaxCacheMem)) - } else { - C.vips_cache_set_max_mem(defaultMaxCacheMem) - } - - if config.MaxCacheSize >= 0 { - C.vips_cache_set_max(C.int(config.MaxCacheSize)) - } else { - C.vips_cache_set_max(defaultMaxCacheSize) - } - - C.vips_cache_set_trace(toGboolean(config.CacheTrace)) - } else { - C.vips_concurrency_set(defaultConcurrencyLevel) - C.vips_cache_set_max(defaultMaxCacheSize) - C.vips_cache_set_max_mem(defaultMaxCacheMem) - C.vips_cache_set_max_files(defaultMaxCacheFiles) - C.vips_cache_set_trace(toGboolean(false)) - } - - govipsLog("govips", LogLevelInfo, fmt.Sprintf("vips %s started with concurrency=%d cache_max_files=%d cache_max_mem=%d cache_max=%d", - Version, - int(C.vips_concurrency_get()), - int(C.vips_cache_get_max_files()), - int(C.vips_cache_get_max_mem()), - int(C.vips_cache_get_max()))) - - initTypes() - return nil -} - -func enableLogging() { - C.vips_set_logging_handler() -} - -func disableLogging() { - C.vips_unset_logging_handler() -} - -// consoleLogging overrides the Govips logging handler and makes glib -// use its default logging handler which outputs everything to console. -// Needed for CI unit testing due to a macOS bug in Go (doesn't clean cgo callbacks on exit) -func consoleLogging() { - C.vips_default_logging_handler() -} - -// Shutdown libvips -func Shutdown() { - hasShutdown = true - - if statCollectorDone != nil { - statCollectorDone <- struct{}{} - } - - initLock.Lock() - defer initLock.Unlock() - - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - if !running { - govipsLog("govips", LogLevelInfo, "warning libvips not started") - return - } - - if temporaryDirectory != "" { - os.RemoveAll(temporaryDirectory) - } - - C.vips_shutdown() - disableLogging() - running = false -} - -// ShutdownThread clears the cache for for the given thread. This needs to be -// called when a thread using vips exits. -func ShutdownThread() { - C.vips_thread_shutdown() -} - -// ClearCache drops the whole operation cache, handy for leak tracking. -func ClearCache() { - C.vips_cache_drop_all() -} - -// SetPipeReadLimit sets the maximum number of bytes libvips will buffer -// when loading from a non-seekable source (a reader without io.Seeker -// passed to LoadImageFromReader). The default is approximately 1 GB. -// Callers processing large non-seekable streams can lower this to bound -// memory usage. -// -// Must be called before any streaming load operations. -func SetPipeReadLimit(bytes int64) { - C.vips_pipe_read_limit_set(C.gint64(bytes)) -} - -// PrintCache prints the whole operation cache to stdout for debugging purposes. -func PrintCache() { - C.vips_cache_print() -} - -// PrintObjectReport outputs all of the current internal objects in libvips -func PrintObjectReport(label string) { - govipsLog("govips", LogLevelInfo, fmt.Sprintf("\n=======================================\nvips live objects: %s...\n", label)) - C.vips_object_print_all() - govipsLog("govips", LogLevelInfo, "=======================================\n\n") -} - -// MemoryStats is a data structure that houses various memory statistics from ReadVipsMemStats() -type MemoryStats struct { - Mem int64 - MemHigh int64 - Files int64 - Allocs int64 -} - -var openImageRefs atomic.Int64 - -// OpenImageRefs returns the number of ImageRef instances that haven't been closed. -func OpenImageRefs() int64 { - return openImageRefs.Load() -} - -// AssertNoLeaks fails the test if any ImageRef instances remain open. -// Call this at the end of tests to catch leaked images. -func AssertNoLeaks(t testing.TB) { - t.Helper() - n := openImageRefs.Load() - if n != 0 { - t.Errorf("govips: %d ImageRef(s) not closed (leaked)", n) - } -} - -// ReadVipsMemStats returns various memory statistics such as allocated memory and open files. -func ReadVipsMemStats(stats *MemoryStats) { - stats.Mem = int64(C.vips_tracked_get_mem()) - stats.MemHigh = int64(C.vips_tracked_get_mem_highwater()) - stats.Allocs = int64(C.vips_tracked_get_allocs()) - stats.Files = int64(C.vips_tracked_get_files()) -} - -func startupIfNeeded() error { - if !running { - govipsLog("govips", LogLevelInfo, "libvips was forcibly started automatically, consider calling Startup/Shutdown yourself") - if err := Startup(nil); err != nil { - return err - } - } - return nil -} - -// InitTypes initializes caches and figures out which image types are supported -func initTypes() { - once.Do(func() { - cType := C.CString("VipsOperation") - defer freeCString(cType) - - for k, v := range ImageTypes { - name := strings.ToLower("VipsForeignLoad" + v) - typeLoaders[name] = k - typeLoaders[name+"buffer"] = k - - cFunc := C.CString(v + "load") - //noinspection GoDeferInLoop - defer freeCString(cFunc) - - ret := C.vips_type_find(cType, cFunc) - - supportedImageTypes[k] = int(ret) != 0 - - if supportedImageTypes[k] { - govipsLog("govips", LogLevelInfo, fmt.Sprintf("registered image type loader type=%s", v)) - } - } - }) -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/govips.h b/vendor/github.com/davidbyttow/govips/v2/vips/govips.h deleted file mode 100644 index 31f42b04c6..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/govips.h +++ /dev/null @@ -1,26 +0,0 @@ - -// clang-format off -// include order matters -#include -#include -#include -// clang-format on - -#if (VIPS_MAJOR_VERSION < 8) -error_requires_version_8 -#endif - - extern void - govipsLoggingHandler(char *log_domain, int log_level, char *message); - -static void govips_logging_handler(const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *message, gpointer user_data); - -static void null_logging_handler(const gchar *log_domain, - GLogLevelFlags log_level, const gchar *message, - gpointer user_data); - -void vips_set_logging_handler(void); -void vips_unset_logging_handler(void); -void vips_default_logging_handler(void); \ No newline at end of file diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/icc_profiles.go b/vendor/github.com/davidbyttow/govips/v2/vips/icc_profiles.go deleted file mode 100644 index 8d5c55fb00..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/icc_profiles.go +++ /dev/null @@ -1,724 +0,0 @@ -package vips - -import ( - "os" - "path/filepath" - "sync" -) - -var ( - // ATTRIBUTION: - // The following micro icc profile taken from: https://github.com/saucecontrol/Compact-ICC-Profiles. - // Read more (very interesting): https://photosauce.net/blog/post/making-a-minimal-srgb-icc-profile-part-1-trim-the-fat-abuse-the-spec - sRGBV2MicroICCProfile = []byte{ - 0x00, 0x00, 0x01, 0xc8, 0x6c, 0x63, 0x6d, 0x73, 0x02, 0x10, 0x00, 0x00, - 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, - 0x07, 0xe2, 0x00, 0x03, 0x00, 0x14, 0x00, 0x09, 0x00, 0x0e, 0x00, 0x1d, - 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, - 0x73, 0x61, 0x77, 0x73, 0x63, 0x74, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x68, 0x61, 0x6e, 0x64, - 0x9d, 0x91, 0x00, 0x3d, 0x40, 0x80, 0xb0, 0x3d, 0x40, 0x74, 0x2c, 0x81, - 0x9e, 0xa5, 0x22, 0x8e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x5f, - 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0x0c, - 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x00, 0x14, - 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x00, 0x14, - 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x14, - 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0x54, 0x00, 0x00, 0x00, 0x14, - 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x60, - 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x60, - 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x60, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, - 0x75, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x43, 0x43, 0x30, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xc9, - 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, - 0x00, 0x00, 0x38, 0xf2, 0x00, 0x00, 0x03, 0x8f, 0x58, 0x59, 0x5a, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x96, 0x00, 0x00, 0xb7, 0x89, - 0x00, 0x00, 0x18, 0xda, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x85, 0x00, 0x00, 0xb6, 0xc4, - 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, - 0x00, 0x00, 0x00, 0x7c, 0x00, 0xf8, 0x01, 0x9c, 0x02, 0x75, 0x03, 0x83, - 0x04, 0xc9, 0x06, 0x4e, 0x08, 0x12, 0x0a, 0x18, 0x0c, 0x62, 0x0e, 0xf4, - 0x11, 0xcf, 0x14, 0xf6, 0x18, 0x6a, 0x1c, 0x2e, 0x20, 0x43, 0x24, 0xac, - 0x29, 0x6a, 0x2e, 0x7e, 0x33, 0xeb, 0x39, 0xb3, 0x3f, 0xd6, 0x46, 0x57, - 0x4d, 0x36, 0x54, 0x76, 0x5c, 0x17, 0x64, 0x1d, 0x6c, 0x86, 0x75, 0x56, - 0x7e, 0x8d, 0x88, 0x2c, 0x92, 0x36, 0x9c, 0xab, 0xa7, 0x8c, 0xb2, 0xdb, - 0xbe, 0x99, 0xca, 0xc7, 0xd7, 0x65, 0xe4, 0x77, 0xf1, 0xf9, 0xff, 0xff, - } - - // ATTRIBUTION: - // The following micro icc profile taken from: https://github.com/saucecontrol/Compact-ICC-Profiles. - // Read more (very interesting): https://photosauce.net/blog/post/making-a-minimal-srgb-icc-profile-part-1-trim-the-fat-abuse-the-spec - sGrayV2MicroICCProfile = []byte{ - 0x00, 0x00, 0x01, 0x50, 0x6c, 0x63, 0x6d, 0x73, 0x02, 0x10, 0x00, 0x00, - 0x6d, 0x6e, 0x74, 0x72, 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20, - 0x07, 0xe2, 0x00, 0x03, 0x00, 0x14, 0x00, 0x09, 0x00, 0x0e, 0x00, 0x1d, - 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, - 0x73, 0x61, 0x77, 0x73, 0x63, 0x74, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x68, 0x61, 0x6e, 0x64, - 0x05, 0xd2, 0x02, 0xa7, 0xf9, 0xdd, 0x47, 0x94, 0xc7, 0x4f, 0x4c, 0x5f, - 0x26, 0x82, 0x3a, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0x5f, - 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x0c, - 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, 0x14, - 0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x60, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, - 0x75, 0x47, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x43, 0x43, 0x30, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xf3, 0x54, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xc9, - 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, - 0x00, 0x00, 0x00, 0x7c, 0x00, 0xf8, 0x01, 0x9c, 0x02, 0x75, 0x03, 0x83, - 0x04, 0xc9, 0x06, 0x4e, 0x08, 0x12, 0x0a, 0x18, 0x0c, 0x62, 0x0e, 0xf4, - 0x11, 0xcf, 0x14, 0xf6, 0x18, 0x6a, 0x1c, 0x2e, 0x20, 0x43, 0x24, 0xac, - 0x29, 0x6a, 0x2e, 0x7e, 0x33, 0xeb, 0x39, 0xb3, 0x3f, 0xd6, 0x46, 0x57, - 0x4d, 0x36, 0x54, 0x76, 0x5c, 0x17, 0x64, 0x1d, 0x6c, 0x86, 0x75, 0x56, - 0x7e, 0x8d, 0x88, 0x2c, 0x92, 0x36, 0x9c, 0xab, 0xa7, 0x8c, 0xb2, 0xdb, - 0xbe, 0x99, 0xca, 0xc7, 0xd7, 0x65, 0xe4, 0x77, 0xf1, 0xf9, 0xff, 0xff, - } - - sRGBIEC6196621ICCProfile = []byte{ - 0x00, 0x00, 0x0b, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, - 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, - 0x07, 0xd9, 0x00, 0x03, 0x00, 0x1b, 0x00, 0x15, 0x00, 0x24, 0x00, 0x1f, - 0x61, 0x63, 0x73, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x00, 0x00, 0x00, 0x00, - 0x29, 0xf8, 0x3d, 0xde, 0xaf, 0xf2, 0x55, 0xae, 0x78, 0x42, 0xfa, 0xe4, - 0xca, 0x83, 0x39, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x44, 0x00, 0x00, 0x00, 0x79, - 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x00, 0x14, - 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xd4, 0x00, 0x00, 0x08, 0x0c, - 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x09, 0xe0, 0x00, 0x00, 0x00, 0x88, - 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x0a, 0x68, 0x00, 0x00, 0x00, 0x14, - 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xd4, 0x00, 0x00, 0x08, 0x0c, - 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x0a, 0x7c, 0x00, 0x00, 0x00, 0x14, - 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x0a, 0x90, 0x00, 0x00, 0x00, 0x24, - 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x0a, 0xb4, 0x00, 0x00, 0x00, 0x14, - 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x0a, 0xc8, 0x00, 0x00, 0x00, 0x14, - 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xd4, 0x00, 0x00, 0x08, 0x0c, - 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x0a, 0xdc, 0x00, 0x00, 0x00, 0x0c, - 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x0a, 0xe8, 0x00, 0x00, 0x00, 0x87, - 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x0b, 0x70, 0x00, 0x00, 0x00, 0x14, - 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x0b, 0x84, 0x00, 0x00, 0x00, 0x37, - 0x63, 0x68, 0x61, 0x64, 0x00, 0x00, 0x0b, 0xbc, 0x00, 0x00, 0x00, 0x2c, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, - 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, - 0x36, 0x2d, 0x32, 0x2d, 0x31, 0x20, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x20, - 0x73, 0x63, 0x61, 0x6c, 0x65, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x24, 0xa0, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xcf, - 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, - 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, - 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, - 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, - 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, - 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, - 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, - 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, - 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, - 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, - 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, - 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, - 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, - 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, - 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, - 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, - 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, - 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, - 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, - 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, - 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, - 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, - 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, - 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, - 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, - 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, - 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, - 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, - 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, - 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, - 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, - 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, - 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, - 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, - 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, - 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, - 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, - 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, - 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0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, 0x14, 0xad, 0x14, 0xce, - 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, - 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, - 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, - 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, - 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, - 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, - 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, - 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, - 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, - 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, - 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, - 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, - 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, - 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, - 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, - 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, - 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, - 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, - 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, - 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, - 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, - 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, - 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, - 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, - 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, - 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, - 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, - 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, - 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, - 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, - 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, - 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, - 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, - 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, - 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, - 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, - 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, - 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, - 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, - 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, - 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, - 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, - 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, - 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, - 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, - 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, - 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, - 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, - 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, - 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, - 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, - 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, - 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, - 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, - 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, - 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, - 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, - 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, - 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, - 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, - 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, - 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, - 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, - 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, - 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, - 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, - 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, - 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, - 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, - 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, - 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, - 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, - 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, - 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, - 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, - 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, - 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x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, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, - 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, - 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, - 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, - 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, - 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, - 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, - 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, - 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, - 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, - 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff, 0x64, 0x65, 0x73, 0x63, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, - 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2d, 0x31, 0x20, 0x44, 0x65, - 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x43, 0x6f, - 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x53, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, - 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x99, - 0x00, 0x00, 0xb7, 0x85, 0x00, 0x00, 0x18, 0xda, 0x58, 0x59, 0x5a, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x03, 0x16, 0x00, 0x00, 0x03, 0x33, 0x00, 0x00, 0x02, 0xa4, - 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa2, - 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x73, 0x69, 0x67, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x52, 0x65, 0x66, 0x65, - 0x72, 0x65, 0x6e, 0x63, 0x65, 0x20, 0x56, 0x69, 0x65, 0x77, 0x69, 0x6e, - 0x67, 0x20, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x20, - 0x69, 0x6e, 0x20, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, - 0x2d, 0x32, 0x2d, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x74, 0x65, 0x78, 0x74, - 0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, - 0x74, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x61, 0x6c, 0x20, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x43, 0x6f, - 0x6e, 0x73, 0x6f, 0x72, 0x74, 0x69, 0x75, 0x6d, 0x2c, 0x20, 0x32, 0x30, - 0x30, 0x39, 0x00, 0x00, 0x73, 0x66, 0x33, 0x32, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x01, 0x0c, 0x44, 0x00, 0x00, 0x05, 0xdf, 0xff, 0xff, 0xf3, 0x26, - 0x00, 0x00, 0x07, 0x94, 0x00, 0x00, 0xfd, 0x8f, 0xff, 0xff, 0xfb, 0xa1, - 0xff, 0xff, 0xfd, 0xa2, 0x00, 0x00, 0x03, 0xdb, 0x00, 0x00, 0xc0, 0x75, - } - - genericGrayGamma22ICCProfile = []byte{ - 0x00, 0x00, 0x0e, 0x04, 0x61, 0x70, 0x70, 0x6c, 0x02, 0x00, 0x00, 0x00, - 0x6d, 0x6e, 0x74, 0x72, 0x47, 0x52, 0x41, 0x59, 0x58, 0x59, 0x5a, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x61, 0x63, 0x73, 0x70, 0x41, 0x50, 0x50, 0x4c, 0x00, 0x00, 0x00, 0x00, - 0x6e, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x70, 0x70, 0x6c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, - 0x6b, 0x54, 0x52, 0x43, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x08, 0x0c, - 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x08, 0xcc, 0x00, 0x00, 0x00, 0x14, - 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x08, 0xe0, 0x00, 0x00, 0x00, 0x23, - 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00, 0x00, 0x79, - 0x64, 0x73, 0x63, 0x6d, 0x00, 0x00, 0x09, 0x80, 0x00, 0x00, 0x04, 0x82, - 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, - 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, - 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, - 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, - 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, - 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, - 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, - 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, - 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, - 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, - 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, - 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, - 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, - 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, - 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, - 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, - 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, - 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, - 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, - 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, - 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, - 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, - 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, - 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, - 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, - 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, - 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, - 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, - 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, - 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, - 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, - 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, - 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, - 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, - 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, - 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, - 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, - 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, - 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, - 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, - 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, - 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, - 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, - 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, - 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, - 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, - 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, - 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, - 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, - 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, - 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, - 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, - 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, - 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, - 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, - 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, - 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, - 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, - 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, - 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, - 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, - 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, - 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, - 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, - 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, - 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, - 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, - 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, - 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, - 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, - 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, - 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, - 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, - 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, - 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, - 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, - 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, - 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, - 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, - 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, - 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, - 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, - 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, - 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, - 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, - 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, - 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, - 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, - 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, - 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, - 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, - 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, - 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, - 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, - 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, - 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, - 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, - 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, - 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, - 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, - 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, - 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, - 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, - 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, - 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, - 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, - 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, - 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, - 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, - 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, - 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, - 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, - 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, - 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, - 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, - 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, - 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, - 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, - 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, - 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, - 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, - 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, - 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, - 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, - 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, - 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, - 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, - 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, - 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, - 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, - 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, - 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, - 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, - 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0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, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, - 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, - 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, - 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, - 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, - 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, - 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, - 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff, 0x58, 0x59, 0x5a, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, - 0x00, 0x01, 0x16, 0xcc, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, - 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x41, 0x70, - 0x70, 0x6c, 0x65, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x2c, 0x20, 0x32, 0x30, - 0x30, 0x38, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x1f, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x20, - 0x47, 0x72, 0x61, 0x79, 0x20, 0x47, 0x61, 0x6d, 0x6d, 0x61, 0x20, 0x32, - 0x2e, 0x32, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x6c, 0x75, 0x63, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x0c, - 0x65, 0x6e, 0x55, 0x53, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xdc, - 0x65, 0x73, 0x45, 0x53, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x01, 0x18, - 0x64, 0x61, 0x44, 0x4b, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x02, 0x2a, - 0x64, 0x65, 0x44, 0x45, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x01, 0xde, - 0x66, 0x69, 0x46, 0x49, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x02, 0xa0, - 0x66, 0x72, 0x46, 0x55, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x02, 0x62, - 0x69, 0x74, 0x49, 0x54, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x03, 0x70, - 0x6e, 0x6c, 0x4e, 0x4c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x01, 0x64, - 0x6e, 0x62, 0x4e, 0x4f, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x03, 0xc4, - 0x70, 0x74, 0x42, 0x52, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x03, 0x26, - 0x73, 0x76, 0x53, 0x45, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x02, 0x2a, - 0x6a, 0x61, 0x4a, 0x50, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x03, 0xfe, - 0x6b, 0x6f, 0x4b, 0x52, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x04, 0x24, - 0x7a, 0x68, 0x54, 0x57, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x04, 0x46, - 0x7a, 0x68, 0x43, 0x4e, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x04, 0x64, - 0x72, 0x75, 0x52, 0x55, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x01, 0xa4, - 0x70, 0x6c, 0x50, 0x4c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x02, 0xe6, - 0x00, 0x47, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x72, 0x00, 0x69, - 0x00, 0x63, 0x00, 0x20, 0x00, 0x47, 0x00, 0x72, 0x00, 0x61, 0x00, 0x79, - 0x00, 0x20, 0x00, 0x47, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, - 0x00, 0x20, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x20, 0x00, 0x50, - 0x00, 0x72, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x65, - 0x00, 0x50, 0x00, 0x65, 0x00, 0x72, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, - 0x00, 0x20, 0x00, 0x67, 0x00, 0x65, 0x00, 0x6e, 0x00, 0xe9, 0x00, 0x72, - 0x00, 0x69, 0x00, 0x63, 0x00, 0x6f, 0x00, 0x20, 0x00, 0x64, 0x00, 0x65, - 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, - 0x00, 0x20, 0x00, 0x64, 0x00, 0x65, 0x00, 0x20, 0x00, 0x67, 0x00, 0x72, - 0x00, 0x69, 0x00, 0x73, 0x00, 0x65, 0x00, 0x73, 0x00, 0x20, 0x00, 0x32, - 0x00, 0x2c, 0x00, 0x32, 0x00, 0x41, 0x00, 0x6c, 0x00, 0x67, 0x00, 0x65, - 0x00, 0x6d, 0x00, 0x65, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x20, 0x00, 0x67, - 0x00, 0x72, 0x00, 0x69, 0x00, 0x6a, 0x00, 0x73, 0x00, 0x20, 0x00, 0x67, - 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x20, 0x00, 0x32, - 0x00, 0x2c, 0x00, 0x32, 0x00, 0x2d, 0x00, 0x70, 0x00, 0x72, 0x00, 0x6f, - 0x00, 0x66, 0x00, 0x69, 0x00, 0x65, 0x00, 0x6c, 0x04, 0x1e, 0x04, 0x31, - 0x04, 0x49, 0x04, 0x30, 0x04, 0x4f, 0x00, 0x20, 0x04, 0x41, 0x04, 0x35, - 0x04, 0x40, 0x04, 0x30, 0x04, 0x4f, 0x00, 0x20, 0x04, 0x33, 0x04, 0x30, - 0x04, 0x3c, 0x04, 0x3c, 0x04, 0x30, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, - 0x00, 0x32, 0x00, 0x2d, 0x04, 0x3f, 0x04, 0x40, 0x04, 0x3e, 0x04, 0x44, - 0x04, 0x38, 0x04, 0x3b, 0x04, 0x4c, 0x00, 0x41, 0x00, 0x6c, 0x00, 0x6c, - 0x00, 0x67, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x65, 0x00, 0x69, 0x00, 0x6e, - 0x00, 0x65, 0x00, 0x73, 0x00, 0x20, 0x00, 0x47, 0x00, 0x72, 0x00, 0x61, - 0x00, 0x75, 0x00, 0x73, 0x00, 0x74, 0x00, 0x75, 0x00, 0x66, 0x00, 0x65, - 0x00, 0x6e, 0x00, 0x70, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, - 0x00, 0x6c, 0x00, 0x20, 0x00, 0x47, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, - 0x00, 0x61, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x47, - 0x00, 0x65, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x72, 0x00, 0x69, 0x00, 0x73, - 0x00, 0x6b, 0x00, 0x20, 0x00, 0x67, 0x00, 0x72, 0x00, 0xe5, 0x00, 0x20, - 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, - 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x70, 0x00, 0x72, 0x00, 0x6f, - 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x50, 0x00, 0x72, 0x00, 0x6f, - 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x20, 0x00, 0x67, 0x00, 0xe9, - 0x00, 0x6e, 0x00, 0xe9, 0x00, 0x72, 0x00, 0x69, 0x00, 0x71, 0x00, 0x75, - 0x00, 0x65, 0x00, 0x20, 0x00, 0x67, 0x00, 0x72, 0x00, 0x69, 0x00, 0x73, - 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, - 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x59, 0x00, 0x6c, - 0x00, 0x65, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x20, - 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x61, - 0x00, 0x6e, 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, - 0x00, 0x61, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x20, - 0x00, 0x2d, 0x00, 0x70, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, - 0x00, 0x69, 0x00, 0x6c, 0x00, 0x69, 0x00, 0x4f, 0x00, 0x67, 0x00, 0xf3, - 0x00, 0x6c, 0x00, 0x6e, 0x00, 0x79, 0x00, 0x20, 0x00, 0x70, 0x00, 0x72, - 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x20, 0x00, 0x73, - 0x00, 0x7a, 0x00, 0x61, 0x00, 0x72, 0x00, 0x6f, 0x01, 0x5b, 0x00, 0x63, - 0x00, 0x69, 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, - 0x00, 0x61, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x50, - 0x00, 0x65, 0x00, 0x72, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x00, 0x20, - 0x00, 0x47, 0x00, 0x65, 0x00, 0x6e, 0x00, 0xe9, 0x00, 0x72, 0x00, 0x69, - 0x00, 0x63, 0x00, 0x6f, 0x00, 0x20, 0x00, 0x64, 0x00, 0x61, 0x00, 0x20, - 0x00, 0x47, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x20, 0x00, 0x64, - 0x00, 0x65, 0x00, 0x20, 0x00, 0x43, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x7a, - 0x00, 0x61, 0x00, 0x73, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, - 0x00, 0x50, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, - 0x00, 0x6f, 0x00, 0x20, 0x00, 0x67, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x65, - 0x00, 0x72, 0x00, 0x69, 0x00, 0x63, 0x00, 0x6f, 0x00, 0x20, 0x00, 0x64, - 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x61, 0x00, 0x20, 0x00, 0x67, - 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x20, 0x00, 0x64, - 0x00, 0x65, 0x00, 0x69, 0x00, 0x20, 0x00, 0x67, 0x00, 0x72, 0x00, 0x69, - 0x00, 0x67, 0x00, 0x69, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, - 0x00, 0x47, 0x00, 0x65, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x72, 0x00, 0x69, - 0x00, 0x73, 0x00, 0x6b, 0x00, 0x20, 0x00, 0x67, 0x00, 0x72, 0x00, 0xe5, - 0x00, 0x20, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6d, 0x00, 0x6d, 0x00, 0x61, - 0x00, 0x20, 0x00, 0x32, 0x00, 0x2c, 0x00, 0x32, 0x00, 0x2d, 0x00, 0x70, - 0x00, 0x72, 0x00, 0x6f, 0x00, 0x66, 0x00, 0x69, 0x00, 0x6c, 0x4e, 0x00, - 0x82, 0x2c, 0x30, 0xb0, 0x30, 0xec, 0x30, 0xa4, 0x30, 0xac, 0x30, 0xf3, - 0x30, 0xde, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x20, - 0x30, 0xd7, 0x30, 0xed, 0x30, 0xd5, 0x30, 0xa1, 0x30, 0xa4, 0x30, 0xeb, - 0xc7, 0x7c, 0xbc, 0x18, 0x00, 0x20, 0xd6, 0x8c, 0xc0, 0xc9, 0x00, 0x20, - 0xac, 0x10, 0xb9, 0xc8, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x32, - 0x00, 0x20, 0xd5, 0x04, 0xb8, 0x5c, 0xd3, 0x0c, 0xc7, 0x7c, 0x90, 0x1a, - 0x75, 0x28, 0x70, 0x70, 0x96, 0x8e, 0x51, 0x49, 0x5e, 0xa6, 0x00, 0x20, - 0x00, 0x32, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x20, 0x82, 0x72, 0x5f, 0x69, - 0x63, 0xcf, 0x8f, 0xf0, 0x90, 0x1a, 0x75, 0x28, 0x70, 0x70, 0x5e, 0xa6, - 0x7c, 0xfb, 0x65, 0x70, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x32, - 0x00, 0x20, 0x63, 0xcf, 0x8f, 0xf0, 0x65, 0x87, 0x4e, 0xf6, 0x00, 0x00, - } - - sRGBV2MicroICCProfilePathToken = "\x00srgb_v2_micro.icc" - sGrayV2MicroICCProfilePathToken = "\x00sgray_v2_micro.icc" - sRGBIEC6196621ICCProfilePathToken = "\x00srgb_iec61966_2_1.icc" - genericGrayGamma22ICCProfilePathToken = "\x00generic_gray_gamma_2_2.icc" - - temporaryDirectory = "" - SRGBV2MicroICCProfilePath = sRGBV2MicroICCProfilePathToken - SGrayV2MicroICCProfilePath = sGrayV2MicroICCProfilePathToken - SRGBIEC6196621ICCProfilePath = sRGBIEC6196621ICCProfilePathToken - GenericGrayGamma22ICCProfilePath = genericGrayGamma22ICCProfilePathToken -) - -// Back support -func ensureLoadICCPath(name *string) (err error) { - if len(*name) > 0 && (*name)[0] == 0 { - switch *name { - case sRGBV2MicroICCProfilePathToken: - *name, err = GetSRGBV2MicroICCProfilePath() - return - case sGrayV2MicroICCProfilePathToken: - *name, err = GetSGrayV2MicroICCProfilePath() - return - case sRGBIEC6196621ICCProfilePathToken: - *name, err = GetSRGBIEC6196621ICCProfilePath() - return - case genericGrayGamma22ICCProfilePathToken: - *name, err = GetGenericGrayGamma22ICCProfilePath() - return - } - } - return -} - -var tempDirOnce sync.Once -var tempDirErr error - -func getTemporaryDirectory() (string, error) { - tempDirOnce.Do(func() { - temporaryDirectory, tempDirErr = os.MkdirTemp("", "govips-") - }) - return temporaryDirectory, tempDirErr -} - -var lockIcc sync.Mutex - -func GetSRGBV2MicroICCProfilePath() (string, error) { - return getOrLoad(&SRGBV2MicroICCProfilePath, "srgb_v2_micro.icc", sRGBV2MicroICCProfile) -} - -func GetSGrayV2MicroICCProfilePath() (string, error) { - return getOrLoad(&SGrayV2MicroICCProfilePath, "sgray_v2_micro.icc", sGrayV2MicroICCProfile) -} - -func GetSRGBIEC6196621ICCProfilePath() (string, error) { - return getOrLoad(&SRGBIEC6196621ICCProfilePath, "srgb_iec61966_2_1.icc", sRGBIEC6196621ICCProfile) -} - -func GetGenericGrayGamma22ICCProfilePath() (string, error) { - return getOrLoad(&GenericGrayGamma22ICCProfilePath, "generic_gray_gamma_2_2.icc", genericGrayGamma22ICCProfile) -} - -func getOrLoad(pathFile *string, name string, fileBytes []byte) (string, error) { - lockIcc.Lock() - defer lockIcc.Unlock() - if len(*pathFile) > 0 && (*pathFile)[0] != 0 { - return *pathFile, nil - } - - if _, err := getTemporaryDirectory(); err != nil { - return "", err - } - - *pathFile = filepath.Join(temporaryDirectory, name) - if err := os.WriteFile(*pathFile, fileBytes, 0600); err != nil { - return "", err - } - return *pathFile, nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image.c b/vendor/github.com/davidbyttow/govips/v2/vips/image.c deleted file mode 100644 index a9046f1eb6..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image.c +++ /dev/null @@ -1,16 +0,0 @@ -#include "image.h" - -int has_alpha_channel(VipsImage *image) { return vips_image_hasalpha(image); } - -void clear_image(VipsImage **image) { - // Reference-counting in libvips: https://www.libvips.org/API/current/using-from-c.html#using-C-ref - // https://docs.gtk.org/gobject/method.Object.unref.html - if (G_IS_OBJECT(*image)) g_object_unref(*image); -} - -VipsImage *create_image_from_memory_copy(const void *data, size_t size, - int width, int height, int bands, - VipsBandFormat format) { - return vips_image_new_from_memory_copy(data, size, width, height, bands, - format); -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image.go b/vendor/github.com/davidbyttow/govips/v2/vips/image.go deleted file mode 100644 index d3a3e6e649..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image.go +++ /dev/null @@ -1,988 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "errors" - "fmt" - "image" - "image/draw" - _ "image/gif" - _ "image/jpeg" - _ "image/png" - "io" - "os" - "runtime" - "strconv" - "strings" - "sync" - "unsafe" - - _ "golang.org/x/image/webp" -) - -const GaussBlurDefaultMinAMpl = 0.2 - -// PreMultiplicationState stores the pre-multiplication band format of the image -type PreMultiplicationState struct { - bandFormat BandFormat -} - -// ImageRef contains a libvips image and manages its lifecycle. -type ImageRef struct { - // NOTE: We keep a reference to this so that the input buffer is - // never garbage collected during processing. Some image loaders use random - // access transcoding and therefore need the original buffer to be in memory. - buf []byte - image *C.VipsImage - format ImageType - originalFormat ImageType - lock sync.Mutex - preMultiplication *PreMultiplicationState - optimizedIccProfile string - - // streamSource is non-nil for sequentially stream-loaded images - // (LoadImageFromReader with AccessSequential): the image pulls - // pixels from the source on demand, so the C source and the Go - // reader stay alive until Close or materialize. See stream.go. - streamSource *streamSourceRef -} - -// ImageMetadata is a data structure holding the width, height, orientation and other metadata of the picture. -type ImageMetadata struct { - Format ImageType - Width int - Height int - Colorspace Interpretation - Orientation int - Pages int -} - -type Parameter struct { - value interface{} - isSet bool -} - -func (p *Parameter) IsSet() bool { - return p.isSet -} - -func (p *Parameter) set(v interface{}) { - p.value = v - p.isSet = true -} - -type BoolParameter struct { - Parameter -} - -func (p *BoolParameter) Set(v bool) { - p.set(v) -} - -func (p *BoolParameter) Get() bool { - return p.value.(bool) -} - -type IntParameter struct { - Parameter -} - -func (p *IntParameter) Set(v int) { - p.set(v) -} - -func (p *IntParameter) Get() int { - return p.value.(int) -} - -type Float64Parameter struct { - Parameter -} - -func (p *Float64Parameter) Set(v float64) { - p.set(v) -} - -func (p *Float64Parameter) Get() float64 { - return p.value.(float64) -} - -// ImportParams are options for loading an image. Some are type-specific. -// For default loading, use NewImportParams() or specify nil -type ImportParams struct { - AutoRotate BoolParameter - FailOnError BoolParameter - Page IntParameter - NumPages IntParameter - Density IntParameter - - JpegShrinkFactor IntParameter - WebpScaleFactor Float64Parameter - HeifThumbnail BoolParameter - SvgUnlimited BoolParameter - Access IntParameter -} - -// NewImportParams creates default ImportParams -func NewImportParams() *ImportParams { - p := &ImportParams{} - p.FailOnError.Set(true) - return p -} - -// OptionString convert import params to option_string -func (i *ImportParams) OptionString() string { - var values []string - if v := i.NumPages; v.IsSet() { - values = append(values, "n="+strconv.Itoa(v.Get())) - } - if v := i.Page; v.IsSet() { - values = append(values, "page="+strconv.Itoa(v.Get())) - } - if v := i.Density; v.IsSet() { - values = append(values, "dpi="+strconv.Itoa(v.Get())) - } - if v := i.FailOnError; v.IsSet() { - values = append(values, "fail="+boolToStr(v.Get())) - } - if v := i.JpegShrinkFactor; v.IsSet() { - values = append(values, "shrink="+strconv.Itoa(v.Get())) - } - if v := i.WebpScaleFactor; v.IsSet() { - values = append(values, "scale="+strconv.FormatFloat(v.Get(), 'f', -1, 64)) - } - if v := i.AutoRotate; v.IsSet() { - values = append(values, "autorotate="+boolToStr(v.Get())) - } - if v := i.SvgUnlimited; v.IsSet() { - values = append(values, "unlimited="+boolToStr(v.Get())) - } - if v := i.HeifThumbnail; v.IsSet() { - values = append(values, "thumbnail="+boolToStr(v.Get())) - } - if v := i.Access; v.IsSet() { - values = append(values, "access="+strconv.Itoa(v.Get())) - } - return strings.Join(values, ",") -} - -func boolToStr(v bool) string { - if v { - return "TRUE" - } - return "FALSE" -} - -// ExportParams are options when exporting an image to file or buffer. -// Deprecated: Use format-specific params -type ExportParams struct { - Format ImageType - Quality int - Compression int - Interlaced bool - Lossless bool - Effort int - StripMetadata bool - OptimizeCoding bool // jpeg param - SubsampleMode SubsampleMode // jpeg param - TrellisQuant bool // jpeg param - OvershootDeringing bool // jpeg param - OptimizeScans bool // jpeg param - QuantTable int // jpeg param - Speed int // avif param -} - -// NewDefaultExportParams creates default values for an export when image type is not JPEG, PNG or WEBP. -// By default, govips creates interlaced, lossy images with a quality of 80/100 and compression of 6/10. -// As these are default values for a wide variety of image formats, their application varies. -// Some formats use the quality parameters, some compression, etc. -// Deprecated: Use format-specific params -func NewDefaultExportParams() *ExportParams { - return &ExportParams{ - Format: ImageTypeUnknown, // defaults to the starting encoder - Quality: 80, - Compression: 6, - Interlaced: true, - Lossless: false, - Effort: 4, - } -} - -// NewDefaultJPEGExportParams creates default values for an export of a JPEG image. -// By default, govips creates interlaced JPEGs with a quality of 80/100. -// Deprecated: Use NewJpegExportParams -func NewDefaultJPEGExportParams() *ExportParams { - return &ExportParams{ - Format: ImageTypeJPEG, - Quality: 80, - Interlaced: true, - } -} - -// NewDefaultPNGExportParams creates default values for an export of a PNG image. -// By default, govips creates non-interlaced PNGs with a compression of 6/10. -// Deprecated: Use NewPngExportParams -func NewDefaultPNGExportParams() *ExportParams { - return &ExportParams{ - Format: ImageTypePNG, - Compression: 6, - Interlaced: false, - } -} - -// NewDefaultWEBPExportParams creates default values for an export of a WEBP image. -// By default, govips creates lossy images with a quality of 75/100. -// Deprecated: Use NewWebpExportParams -func NewDefaultWEBPExportParams() *ExportParams { - return &ExportParams{ - Format: ImageTypeWEBP, - Quality: 75, - Lossless: false, - Effort: 4, - } -} - -// JpegExportParams are options when exporting a JPEG to file or buffer -type JpegExportParams struct { - StripMetadata bool - Quality int - Interlace bool - OptimizeCoding bool - SubsampleMode SubsampleMode - TrellisQuant bool - OvershootDeringing bool - OptimizeScans bool - QuantTable int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewJpegExportParams creates default values for an export of a JPEG image. -// By default, govips creates interlaced JPEGs with a quality of 80/100. -func NewJpegExportParams() *JpegExportParams { - return &JpegExportParams{ - Quality: 80, - Interlace: true, - } -} - -// PngExportParams are options when exporting a PNG to file or buffer -type PngExportParams struct { - StripMetadata bool - Compression int - Filter PngFilter - Interlace bool - Quality int - Palette bool - Dither float64 - Bitdepth int - Profile string - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewPngExportParams creates default values for an export of a PNG image. -// By default, govips creates non-interlaced PNGs with a compression of 6/10. -func NewPngExportParams() *PngExportParams { - return &PngExportParams{ - Compression: 6, - Filter: PngFilterNone, - Interlace: false, - Palette: false, - } -} - -// WebpExportParams are options when exporting a WEBP to file or buffer -// see https://www.libvips.org/API/current/VipsForeignSave.html#vips-webpsave -// for details on each parameter -type WebpExportParams struct { - StripMetadata bool - Quality int - Lossless bool - NearLossless bool - ReductionEffort int - IccProfile string - MinSize bool - MinKeyFrames int - MaxKeyFrames int - // TargetSize is the desired output size in bytes (libvips's webpsave - // "target_size" option, passed straight through to libwebp's own - // WebPConfig.target_size). When set (> 0), it takes precedence over - // Quality: libwebp runs its own internal search over the quality range, - // using more encoding passes, to produce output close to this size. It - // is a best effort: the resulting size may still land above or below - // the target. Leave at 0 (the default) to encode at Quality instead. - // - // Requires libvips 8.17.4+ (when target_size was added to webpsave); - // ExportWebp returns an error if TargetSize is set on an older libvips. - TargetSize int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata decides, - // as for the other formats: the source image's ICC profile is kept - // unless StripMetadata is set. A profile from IccProfile or - // OptimizeICCProfile replaces the source profile and is embedded even - // when StripMetadata is set. When set, Keep takes precedence over - // StripMetadata, and it - // alone decides whether an ICC profile is written: without - // ForeignKeepIcc no profile is embedded, whatever its source. With - // ForeignKeepIcc, the embedded profile is the one the path already - // chooses: ExportWebp uses the profile picked by OptimizeICCProfile - // (and ignores IccProfile, as before), while SaveToWriterWebp uses - // IccProfile. With neither, the source image's profile is kept. - // Requires libvips 8.15+; saving returns an error if Keep is set on an - // older libvips. - Keep ForeignKeep -} - -// NewWebpExportParams creates default values for an export of a WEBP image. -// By default, govips creates lossy images with a quality of 75/100. -func NewWebpExportParams() *WebpExportParams { - return &WebpExportParams{ - Quality: 75, - Lossless: false, - NearLossless: false, - ReductionEffort: 4, - } -} - -// TiffExportParams are options when exporting a TIFF to file or buffer -type TiffExportParams struct { - StripMetadata bool - Quality int - Compression TiffCompression - Predictor TiffPredictor - Pyramid bool - Tile bool - TileHeight int - TileWidth int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewTiffExportParams creates default values for an export of a TIFF image. -func NewTiffExportParams() *TiffExportParams { - return &TiffExportParams{ - Quality: 80, - Compression: TiffCompressionLzw, - Predictor: TiffPredictorHorizontal, - Pyramid: false, - Tile: false, - TileHeight: 256, - TileWidth: 256, - } -} - -// GifExportParams are options when exporting a GIF to file or buffer. -// -// For vips 8.12+, native gifsave is used. The relevant parameters are Dither, -// Effort, and Bitdepth. Quality is ignored because native gifsave does not -// support a quality parameter. -// -// For vips below 8.12, magicksave is used as a fallback. The relevant -// parameters are Quality and Bitdepth. -// -// StripMetadata has no effect on GIF images. -type GifExportParams struct { - StripMetadata bool - // Quality is only used with vips < 8.12 (magicksave fallback). - // Ignored by native gifsave in vips 8.12+. - Quality int - Dither float64 - Effort int - Bitdepth int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewGifExportParams creates default values for an export of a GIF image. -func NewGifExportParams() *GifExportParams { - return &GifExportParams{ - Quality: 75, - Effort: 7, - Bitdepth: 8, - } -} - -// HeifExportParams are options when exporting a HEIF to file or buffer -type HeifExportParams struct { - Quality int - Bitdepth int - Effort int - Lossless bool - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewHeifExportParams creates default values for an export of a HEIF image. -func NewHeifExportParams() *HeifExportParams { - return &HeifExportParams{ - Quality: 80, - Bitdepth: 8, - Effort: 5, - Lossless: false, - } -} - -// AvifExportParams are options when exporting an AVIF to file or buffer. -type AvifExportParams struct { - StripMetadata bool - Quality int - Bitdepth int - Effort int - Lossless bool - - // DEPRECATED - Use Effort instead. - Speed int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewAvifExportParams creates default values for an export of an AVIF image. -func NewAvifExportParams() *AvifExportParams { - return &AvifExportParams{ - Quality: 80, - Bitdepth: 8, - Effort: 5, - Lossless: false, - } -} - -// Jp2kExportParams are options when exporting an JPEG2000 to file or buffer. -type Jp2kExportParams struct { - Quality int - Lossless bool - TileWidth int - TileHeight int - SubsampleMode SubsampleMode - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewJp2kExportParams creates default values for an export of an JPEG2000 image. -func NewJp2kExportParams() *Jp2kExportParams { - return &Jp2kExportParams{ - Quality: 80, - Lossless: false, - TileWidth: 512, - TileHeight: 512, - } -} - -// JxlExportParams are options when exporting an JXL to file or buffer. -type JxlExportParams struct { - Quality int - Lossless bool - Tier int - Distance float64 - Effort int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewJxlExportParams creates default values for an export of an JXL image. -func NewJxlExportParams() *JxlExportParams { - return &JxlExportParams{ - Quality: 75, - Lossless: false, - Effort: 7, - Distance: 1.0, - } -} - -// MagickExportParams are options when exporting an image to file or buffer by ImageMagick. -type MagickExportParams struct { - Quality int - Format string - OptimizeGifFrames bool - OptimizeGifTransparency bool - BitDepth int - - // Keep selects which metadata to retain (libvips's "keep" option; see - // ForeignKeep). The zero value leaves it unset, so StripMetadata (where - // present) decides as before. When set, it takes precedence over - // StripMetadata. Requires libvips 8.15+; saving returns an error if Keep - // is set on an older libvips. - Keep ForeignKeep -} - -// NewMagickExportParams creates default values for an export of an image by ImageMagick. -func NewMagickExportParams() *MagickExportParams { - return &MagickExportParams{ - Quality: 75, - } -} - -// NewImageFromReader loads an ImageRef from the given reader by reading -// the entire stream into memory first (io.ReadAll). For large inputs -// prefer LoadImageFromReader, which streams compressed bytes through -// libvips without buffering the whole input in Go memory. -func NewImageFromReader(r io.Reader) (*ImageRef, error) { - buf, err := io.ReadAll(r) - if err != nil { - return nil, err - } - - return NewImageFromBuffer(buf) -} - -// NewImageFromFile loads an image from file and creates a new ImageRef -func NewImageFromFile(file string) (*ImageRef, error) { - return LoadImageFromFile(file, nil) -} - -// LoadImageFromFile loads an image from file and creates a new ImageRef -func LoadImageFromFile(file string, params *ImportParams) (*ImageRef, error) { - buf, err := os.ReadFile(file) - if err != nil { - return nil, err - } - - govipsLog("govips", LogLevelDebug, fmt.Sprintf("creating imageRef from file %s", file)) - return LoadImageFromBuffer(buf, params) -} - -// NewImageFromBuffer loads an image buffer and creates a new Image -func NewImageFromBuffer(buf []byte) (*ImageRef, error) { - return LoadImageFromBuffer(buf, nil) -} - -// LoadImageFromBuffer loads an image buffer and creates a new Image -func LoadImageFromBuffer(buf []byte, params *ImportParams) (*ImageRef, error) { - if err := startupIfNeeded(); err != nil { - return nil, err - } - - if params == nil { - params = NewImportParams() - } - - vipsImage, currentFormat, originalFormat, err := vipsLoadFromBuffer(buf, params) - if err != nil { - return nil, err - } - - ref := newImageRef(vipsImage, currentFormat, originalFormat, buf) - - govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageRef %p", ref)) - return ref, nil -} - -// NewThumbnailFromFile loads an image from file and creates a new ImageRef with thumbnail crop -func NewThumbnailFromFile(file string, width, height int, crop Interesting) (*ImageRef, error) { - return LoadThumbnailFromFile(file, width, height, crop, SizeBoth, nil) -} - -// NewThumbnailFromBuffer loads an image buffer and creates a new Image with thumbnail crop -func NewThumbnailFromBuffer(buf []byte, width, height int, crop Interesting) (*ImageRef, error) { - return LoadThumbnailFromBuffer(buf, width, height, crop, SizeBoth, nil) -} - -// NewThumbnailWithSizeFromFile loads an image from file and creates a new ImageRef with thumbnail crop and size -func NewThumbnailWithSizeFromFile(file string, width, height int, crop Interesting, size Size) (*ImageRef, error) { - return LoadThumbnailFromFile(file, width, height, crop, size, nil) -} - -// LoadThumbnailFromFile loads an image from file and creates a new ImageRef with thumbnail crop and size -func LoadThumbnailFromFile(file string, width, height int, crop Interesting, size Size, params *ImportParams) (*ImageRef, error) { - if err := startupIfNeeded(); err != nil { - return nil, err - } - - vipsImage, format, err := vipsThumbnailFromFile(file, width, height, crop, size, params) - if err != nil { - return nil, err - } - - ref := newImageRef(vipsImage, format, format, nil) - - govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageref %p", ref)) - return ref, nil -} - -// NewThumbnailWithSizeFromBuffer loads an image buffer and creates a new Image with thumbnail crop and size -func NewThumbnailWithSizeFromBuffer(buf []byte, width, height int, crop Interesting, size Size) (*ImageRef, error) { - return LoadThumbnailFromBuffer(buf, width, height, crop, size, nil) -} - -// LoadThumbnailFromBuffer loads an image buffer and creates a new Image with thumbnail crop and size -func LoadThumbnailFromBuffer(buf []byte, width, height int, crop Interesting, size Size, params *ImportParams) (*ImageRef, error) { - if err := startupIfNeeded(); err != nil { - return nil, err - } - - vipsImage, format, err := vipsThumbnailFromBuffer(buf, width, height, crop, size, params) - if err != nil { - return nil, err - } - - ref := newImageRef(vipsImage, format, format, buf) - - govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageref %p", ref)) - return ref, nil -} - -// Metadata returns the metadata (ImageMetadata struct) of the associated ImageRef -func (r *ImageRef) Metadata() *ImageMetadata { - return &ImageMetadata{ - Format: r.Format(), - Width: r.Width(), - Height: r.Height(), - Orientation: r.Orientation(), - Colorspace: r.ColorSpace(), - Pages: r.Pages(), - } -} - -// Copy creates a new copy of the given image. -func (r *ImageRef) Copy() (*ImageRef, error) { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return nil, err - } - - return newImageRef(out, r.format, r.originalFormat, r.buf), nil -} - -// Copy creates a new copy of the given image with the new X and Y resolution (PPI). -func (r *ImageRef) CopyChangingResolution(xres, yres float64) (*ImageRef, error) { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, &CopyOptions{Xres: &xres, Yres: &yres}) - if err != nil { - return nil, err - } - - return newImageRef(out, r.format, r.originalFormat, r.buf), nil -} - -// Copy creates a new copy of the given image with the interpretation. -func (r *ImageRef) CopyChangingInterpretation(interpretation Interpretation) (*ImageRef, error) { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, &CopyOptions{Interpretation: &interpretation}) - if err != nil { - return nil, err - } - - return newImageRef(out, r.format, r.originalFormat, r.buf), nil -} - -// XYZ creates a two-band uint32 image where the elements in the first band have the value of their x coordinate -// and elements in the second band have their y coordinate. -func XYZ(width, height int) (*ImageRef, error) { - vipsImage, err := vipsGenXyz(width, height, nil) - return newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), err -} - -// Identity creates an identity lookup table, which will leave an image unchanged when applied with Maplut. -// Each entry in the table has a value equal to its position. -func Identity(ushort bool) (*ImageRef, error) { - img, err := vipsGenIdentity(&IdentityOptions{Ushort: &ushort}) - return newImageRef(img, ImageTypeUnknown, ImageTypeUnknown, nil), err -} - -// Black creates a new black image of the specified size -func Black(width, height int) (*ImageRef, error) { - vipsImage, err := vipsGenBlack(width, height, nil) - if err != nil { - return nil, err - } - return newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), nil -} - -// Grey creates a horizontal gradient image (ramp from black to white). -// When uchar is true, pixel values are 0-255 uint8; when false, 0.0-1.0 float. -// Useful for creating gradient overlays when combined with rotation, BandJoin, and Composite. -func Grey(width, height int, uchar bool) (*ImageRef, error) { - img, err := vipsGenGrey(width, height, &GreyOptions{Uchar: &uchar}) - if err != nil { - return nil, err - } - return newImageRef(img, ImageTypeUnknown, ImageTypeUnknown, nil), nil -} - -// NewTransparentCanvas creates a fully transparent RGBA image of the given dimensions. -// The image is in sRGB color space with 4 bands (RGBA), all channels set to 0. -func NewTransparentCanvas(width, height int) (*ImageRef, error) { - ref, err := Black(width, height) - if err != nil { - return nil, err - } - - if err := ref.ToColorSpace(InterpretationSRGB); err != nil { - ref.Close() - return nil, err - } - - if err := ref.BandJoinConst([]float64{0}); err != nil { - ref.Close() - return nil, err - } - - return ref, nil -} - -// Text draws the string text to an image. -func Text(params *TextParams) (*ImageRef, error) { - img, err := vipsText(params) - return newImageRef(img, ImageTypeUnknown, ImageTypeUnknown, nil), err -} - -// NewImageFromGoImage creates a new ImageRef from a Go image.Image. -// The image is normalized to NRGBA (non-premultiplied RGBA, 8-bit) and -// imported into libvips in sRGB color space. -func NewImageFromGoImage(img image.Image) (*ImageRef, error) { - if err := startupIfNeeded(); err != nil { - return nil, err - } - - bounds := img.Bounds() - width := bounds.Dx() - height := bounds.Dy() - - if width == 0 || height == 0 { - return nil, errors.New("image has zero dimensions") - } - - // Normalize to NRGBA - var nrgba *image.NRGBA - if n, ok := img.(*image.NRGBA); ok && n.Rect.Min.X == 0 && n.Rect.Min.Y == 0 && n.Stride == width*4 { - nrgba = n - } else { - nrgba = image.NewNRGBA(image.Rect(0, 0, width, height)) - draw.Draw(nrgba, nrgba.Bounds(), img, bounds.Min, draw.Src) - } - - // Create vips image from pixel data (copies data, safe for Go GC) - vipsImage := C.create_image_from_memory_copy( - unsafe.Pointer(&nrgba.Pix[0]), - C.size_t(len(nrgba.Pix)), - C.int(width), - C.int(height), - 4, - C.VIPS_FORMAT_UCHAR, - ) - runtime.KeepAlive(nrgba) - if vipsImage == nil { - return nil, errors.New("failed to create vips image from memory") - } - - // Set interpretation to sRGB - vipsImage.Type = C.VIPS_INTERPRETATION_sRGB - - return newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), nil -} - -// NewImageFromMemory creates a new ImageRef from a raw, uncompressed pixel -// buffer. The buffer is interpreted as height rows of width pixels, each pixel -// holding bands samples of the given BandFormat, laid out contiguously (no row -// stride padding). -// -// Use this for raw byte arrays from sources like ML inference outputs (ONNX, -// TensorFlow), camera sensors, or any in-memory pixel data. For Go's -// image.Image, use NewImageFromGoImage. For compressed bytes (PNG, JPEG, etc.), -// use NewImageFromBuffer. -// -// The pixel data is copied into libvips, so the caller is free to reuse or -// free the input slice after this call returns. -func NewImageFromMemory(pixels []byte, width, height, bands int, format BandFormat, interpretation Interpretation) (*ImageRef, error) { - if err := startupIfNeeded(); err != nil { - return nil, err - } - - if width <= 0 || height <= 0 || bands <= 0 { - return nil, fmt.Errorf("invalid dimensions: width=%d height=%d bands=%d", width, height, bands) - } - - bytesPerSample, ok := bandFormatSizes[format] - if !ok { - return nil, fmt.Errorf("unsupported band format: %d", format) - } - - expected := width * height * bands * bytesPerSample - if len(pixels) != expected { - return nil, fmt.Errorf("pixel buffer size mismatch: got %d bytes, expected %d (%dx%dx%d samples of %d bytes)", - len(pixels), expected, width, height, bands, bytesPerSample) - } - - vipsImage := C.create_image_from_memory_copy( - unsafe.Pointer(&pixels[0]), - C.size_t(len(pixels)), - C.int(width), - C.int(height), - C.int(bands), - C.VipsBandFormat(format), - ) - runtime.KeepAlive(pixels) - if vipsImage == nil { - return nil, errors.New("failed to create vips image from memory") - } - - vipsImage.Type = C.VipsInterpretation(interpretation) - - return newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), nil -} - -// bandFormatSizes is the byte size of one sample for each supported BandFormat. -// Complex/DPComplex are excluded — vips_image_new_from_memory rejects them in -// practice and the size depends on real/imag pairing semantics. -var bandFormatSizes = map[BandFormat]int{ - BandFormatUchar: 1, - BandFormatChar: 1, - BandFormatUshort: 2, - BandFormatShort: 2, - BandFormatUint: 4, - BandFormatInt: 4, - BandFormatFloat: 4, - BandFormatDouble: 8, -} - -func newImageRef(vipsImage *C.VipsImage, currentFormat ImageType, originalFormat ImageType, buf []byte) *ImageRef { - imageRef := &ImageRef{ - image: vipsImage, - format: currentFormat, - originalFormat: originalFormat, - buf: buf, - } - openImageRefs.Add(1) - runtime.SetFinalizer(imageRef, finalizeImage) - - return imageRef -} - -func finalizeImage(ref *ImageRef) { - govipsLog("govips", LogLevelDebug, fmt.Sprintf("closing image %p", ref)) - ref.Close() -} - -// Close manually closes the image and frees the memory. Calling Close() is optional. -// Images are automatically closed by GC. However, in high volume applications the GC -// can't keep up with the amount of memory, so you might want to manually close the images. -func (r *ImageRef) Close() { - r.lock.Lock() - - if r.image != nil { - clearImage(r.image) - r.image = nil - openImageRefs.Add(-1) - } - - r.buf = nil - - // Release the streaming source only after the image is gone: the - // image may still hold references that read from the source. - src := r.streamSource - r.streamSource = nil - - r.lock.Unlock() - - if src != nil { - src.release() - } -} - -// SetKill sets the libvips kill flag used to stop image evaluation. -func (r *ImageRef) SetKill(kill bool) { - r.lock.Lock() - defer r.lock.Unlock() - - if r.image != nil { - C.vips_image_set_kill(r.image, toGboolean(kill)) - } -} - -// setImage resets the image for this image and frees the previous one -func (r *ImageRef) setImage(image *C.VipsImage) { - r.lock.Lock() - defer r.lock.Unlock() - - if r.image == image { - return - } - - if r.image != nil { - clearImage(r.image) - } - - r.image = image -} - -func vipsHasAlpha(in *C.VipsImage) bool { - return int(C.has_alpha_channel(in)) > 0 -} - -func clearImage(ref *C.VipsImage) { - C.clear_image(&ref) -} - -// vipsRefCount reads the GObject reference count. Test-only: it lets tests -// catch a stray unref without relying on a use-after-free to crash. -func vipsRefCount(in *C.VipsImage) int { - return int((*C.GObject)(unsafe.Pointer(in)).ref_count) -} - -// Coding represents VIPS_CODING type -type Coding int - -// Coding enum -// -//goland:noinspection GoUnusedConst -const ( - CodingError Coding = C.VIPS_CODING_ERROR - CodingNone Coding = C.VIPS_CODING_NONE - CodingLABQ Coding = C.VIPS_CODING_LABQ - CodingRAD Coding = C.VIPS_CODING_RAD -) - -func (r *ImageRef) newMetadata(format ImageType) *ImageMetadata { - return &ImageMetadata{ - Format: format, - Width: r.Width(), - Height: r.Height(), - Colorspace: r.ColorSpace(), - Orientation: r.Orientation(), - Pages: r.Pages(), - } -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image.h b/vendor/github.com/davidbyttow/govips/v2/vips/image.h deleted file mode 100644 index e8c8aa5be0..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image.h +++ /dev/null @@ -1,12 +0,0 @@ -// https://libvips.github.io/libvips/API/current/VipsImage.html - -#include -#include - -int has_alpha_channel(VipsImage *image); - -void clear_image(VipsImage **image); - -VipsImage *create_image_from_memory_copy(const void *data, size_t size, - int width, int height, int bands, - VipsBandFormat format); diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_color.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_color.go deleted file mode 100644 index 8ce388f20d..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_color.go +++ /dev/null @@ -1,173 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "errors" - "runtime" -) - -// ToColorSpace changes the color space of the image to the interpretation supplied as the parameter. -func (r *ImageRef) ToColorSpace(interpretation Interpretation) error { - defer runtime.KeepAlive(r) - out, err := vipsToColorSpace(r.image, interpretation) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Flatten removes the alpha channel from the image and replaces it with the background color -func (r *ImageRef) Flatten(backgroundColor *Color) error { - defer runtime.KeepAlive(r) - opts := &FlattenOptions{} - if backgroundColor != nil { - opts.Background = []float64{float64(backgroundColor.R), float64(backgroundColor.G), float64(backgroundColor.B)} - } - out, err := vipsGenFlatten(r.image, opts) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Modulate the colors -func (r *ImageRef) Modulate(brightness, saturation, hue float64) error { - defer runtime.KeepAlive(r) - var err error - var multiplications []float64 - var additions []float64 - - colorspace := r.ColorSpace() - if colorspace == InterpretationRGB { - colorspace = InterpretationSRGB - } - - multiplications = []float64{brightness, saturation, 1} - additions = []float64{0, 0, hue} - - if r.HasAlpha() { - multiplications = append(multiplications, 1) - additions = append(additions, 0) - } - - err = r.ToColorSpace(InterpretationLCH) - if err != nil { - return err - } - - err = r.Linear(multiplications, additions) - if err != nil { - return err - } - - err = r.ToColorSpace(colorspace) - if err != nil { - return err - } - - return nil -} - -// ModulateHSV modulates the image HSV values based on the supplier parameters. -func (r *ImageRef) ModulateHSV(brightness, saturation float64, hue int) error { - defer runtime.KeepAlive(r) - var err error - var multiplications []float64 - var additions []float64 - - colorspace := r.ColorSpace() - if colorspace == InterpretationRGB { - colorspace = InterpretationSRGB - } - - if r.HasAlpha() { - multiplications = []float64{1, saturation, brightness, 1} - additions = []float64{float64(hue), 0, 0, 0} - } else { - multiplications = []float64{1, saturation, brightness} - additions = []float64{float64(hue), 0, 0} - } - - err = r.ToColorSpace(InterpretationHSV) - if err != nil { - return err - } - - err = r.Linear(multiplications, additions) - if err != nil { - return err - } - - err = r.ToColorSpace(colorspace) - if err != nil { - return err - } - - return nil -} - -// Invert inverts the image -func (r *ImageRef) Invert() error { - defer runtime.KeepAlive(r) - out, err := vipsGenInvert(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Adjusts the image's gamma value. -// See https://www.libvips.org/API/current/libvips-conversion.html#vips-gamma -func (r *ImageRef) Gamma(gamma float64) error { - defer runtime.KeepAlive(r) - out, err := vipsGenGamma(r.image, &GammaOptions{Exponent: &gamma}) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Linear passes an image through a linear transformation (i.e. output = input * a + b). -// See https://libvips.github.io/libvips/API/current/libvips-arithmetic.html#vips-linear -func (r *ImageRef) Linear(a, b []float64) error { - defer runtime.KeepAlive(r) - if len(a) != len(b) { - return errors.New("a and b must be of same length") - } - - out, err := vipsGenLinear(r.image, a, b, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Linear1 runs Linear() with a single constant. -// See https://libvips.github.io/libvips/API/current/libvips-arithmetic.html#vips-linear1 -func (r *ImageRef) Linear1(a, b float64) error { - defer runtime.KeepAlive(r) - out, err := vipsGenLinear(r.image, []float64{a}, []float64{b}, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Cast converts the image to a target band format -func (r *ImageRef) Cast(format BandFormat) error { - defer runtime.KeepAlive(r) - out, err := vipsGenCast(r.image, format, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_composite.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_composite.go deleted file mode 100644 index db4a347107..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_composite.go +++ /dev/null @@ -1,75 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import "runtime" - -// CompositeMulti composites the given overlay image on top of the associated image with provided blending mode. -func (r *ImageRef) CompositeMulti(ins []*ImageComposite) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(ins) - out, err := vipsComposite(toVipsCompositeStructs(r, ins)) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Composite composites the given overlay image on top of the associated image with provided blending mode. -func (r *ImageRef) Composite(overlay *ImageRef, mode BlendMode, x, y int) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(overlay) - out, err := vipsGenComposite2(r.image, overlay.image, mode, &Composite2Options{X: &x, Y: &y}) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Insert draws the image on top of the associated image at the given coordinates. -func (r *ImageRef) Insert(sub *ImageRef, x, y int, expand bool, background *ColorRGBA) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(sub) - insertOpts := &InsertOptions{Expand: &expand} - if background != nil { - insertOpts.Background = []float64{float64(background.R), float64(background.G), float64(background.B), float64(background.A)} - } - out, err := vipsGenInsert(r.image, sub.image, x, y, insertOpts) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Join joins this image with another in the direction specified -func (r *ImageRef) Join(in *ImageRef, dir Direction) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(in) - out, err := vipsJoin(r.image, in.image, dir) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// ArrayJoin joins an array of images together wrapping at each n images -func (r *ImageRef) ArrayJoin(images []*ImageRef, across int) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(images) - allImages := append([]*ImageRef{r}, images...) - inputs := make([]*C.VipsImage, len(allImages)) - for i := range inputs { - inputs[i] = allImages[i].image - } - out, err := vipsGenArrayjoin(inputs, &ArrayjoinOptions{Across: &across}) - if err != nil { - return err - } - r.setImage(out) - return nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_export.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_export.go deleted file mode 100644 index f866def302..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_export.go +++ /dev/null @@ -1,439 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "bytes" - "errors" - "fmt" - "image" - "runtime" - "unsafe" -) - -// Export creates a byte array of the image for use. -// The function returns a byte array that can be written to a file e.g. via os.WriteFile(). -// N.B. govips does not currently have built-in support for directly exporting to a file. -// The function also returns a copy of the image metadata as well as an error. -// Deprecated: Use ExportNative or format-specific Export methods -func (r *ImageRef) Export(params *ExportParams) ([]byte, *ImageMetadata, error) { - if params == nil || params.Format == ImageTypeUnknown { - return r.ExportNative() - } - - format := params.Format - - if !IsTypeSupported(format) { - return nil, r.newMetadata(ImageTypeUnknown), fmt.Errorf("cannot save to %#v", ImageTypes[format]) - } - - switch format { - case ImageTypeGIF: - return r.ExportGIF(gifParamsFromExport(params)) - case ImageTypeWEBP: - return r.ExportWebp(webpParamsFromExport(params)) - case ImageTypePNG: - return r.ExportPng(pngParamsFromExport(params)) - case ImageTypeTIFF: - return r.ExportTiff(tiffParamsFromExport(params)) - case ImageTypeHEIF: - return r.ExportHeif(heifParamsFromExport(params)) - case ImageTypeAVIF: - return r.ExportAvif(&AvifExportParams{ - StripMetadata: params.StripMetadata, - Quality: params.Quality, - Lossless: params.Lossless, - Speed: params.Speed, - }) - case ImageTypeJXL: - return r.ExportJxl(&JxlExportParams{ - Quality: params.Quality, - Lossless: params.Lossless, - Effort: params.Effort, - }) - default: - format = ImageTypeJPEG - return r.ExportJpeg(jpegParamsFromExport(params)) - } -} - -// The *ParamsFromExport helpers map the generic (deprecated) ExportParams -// onto format-specific params. They are shared between Export and the -// streaming SaveToWriter so the two paths cannot drift. A nil params -// yields the format's defaults. - -func jpegParamsFromExport(params *ExportParams) *JpegExportParams { - if params == nil { - return NewJpegExportParams() - } - return &JpegExportParams{ - Quality: params.Quality, - StripMetadata: params.StripMetadata, - Interlace: params.Interlaced, - OptimizeCoding: params.OptimizeCoding, - SubsampleMode: params.SubsampleMode, - TrellisQuant: params.TrellisQuant, - OvershootDeringing: params.OvershootDeringing, - OptimizeScans: params.OptimizeScans, - QuantTable: params.QuantTable, - } -} - -func pngParamsFromExport(params *ExportParams) *PngExportParams { - if params == nil { - return NewPngExportParams() - } - return &PngExportParams{ - StripMetadata: params.StripMetadata, - Compression: params.Compression, - Interlace: params.Interlaced, - } -} - -func webpParamsFromExport(params *ExportParams) *WebpExportParams { - if params == nil { - return NewWebpExportParams() - } - return &WebpExportParams{ - StripMetadata: params.StripMetadata, - Quality: params.Quality, - Lossless: params.Lossless, - ReductionEffort: params.Effort, - } -} - -func tiffParamsFromExport(params *ExportParams) *TiffExportParams { - if params == nil { - return NewTiffExportParams() - } - compression := TiffCompressionLzw - if params.Lossless { - compression = TiffCompressionNone - } - return &TiffExportParams{ - StripMetadata: params.StripMetadata, - Quality: params.Quality, - Compression: compression, - } -} - -func heifParamsFromExport(params *ExportParams) *HeifExportParams { - if params == nil { - return NewHeifExportParams() - } - return &HeifExportParams{ - Quality: params.Quality, - Lossless: params.Lossless, - } -} - -func gifParamsFromExport(params *ExportParams) *GifExportParams { - if params == nil { - return NewGifExportParams() - } - return &GifExportParams{ - Quality: params.Quality, - } -} - -// ExportNative exports the image to a buffer based on its native format with default parameters. -func (r *ImageRef) ExportNative() ([]byte, *ImageMetadata, error) { - switch r.format { - case ImageTypeJPEG: - return r.ExportJpeg(NewJpegExportParams()) - case ImageTypePNG: - return r.ExportPng(NewPngExportParams()) - case ImageTypeWEBP: - return r.ExportWebp(NewWebpExportParams()) - case ImageTypeHEIF: - return r.ExportHeif(NewHeifExportParams()) - case ImageTypeTIFF: - return r.ExportTiff(NewTiffExportParams()) - case ImageTypeAVIF: - return r.ExportAvif(NewAvifExportParams()) - case ImageTypeJP2K: - return r.ExportJp2k(NewJp2kExportParams()) - case ImageTypeGIF: - return r.ExportGIF(NewGifExportParams()) - case ImageTypeJXL: - return r.ExportJxl(NewJxlExportParams()) - default: - return r.ExportJpeg(NewJpegExportParams()) - } -} - -// ExportJpeg exports the image as JPEG to a buffer. -func (r *ImageRef) ExportJpeg(params *JpegExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewJpegExportParams() - } - - buf, err := vipsSaveJPEGToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeJPEG), nil -} - -// ExportPng exports the image as PNG to a buffer. -func (r *ImageRef) ExportPng(params *PngExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewPngExportParams() - } - - buf, err := vipsSavePNGToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypePNG), nil -} - -// ExportWebp exports the image as WEBP to a buffer. -func (r *ImageRef) ExportWebp(params *WebpExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewWebpExportParams() - } - - paramsWithIccProfile := *params - paramsWithIccProfile.IccProfile = r.optimizedIccProfile - - buf, err := vipsSaveWebPToBuffer(r.image, paramsWithIccProfile) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeWEBP), nil -} - -// ExportHeif exports the image as HEIF to a buffer. -func (r *ImageRef) ExportHeif(params *HeifExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewHeifExportParams() - } - - buf, err := vipsSaveHEIFToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeHEIF), nil -} - -// ExportTiff exports the image as TIFF to a buffer. -func (r *ImageRef) ExportTiff(params *TiffExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewTiffExportParams() - } - - buf, err := vipsSaveTIFFToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeTIFF), nil -} - -// ExportGIF exports the image as GIF to a buffer. -func (r *ImageRef) ExportGIF(params *GifExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewGifExportParams() - } - - buf, err := vipsSaveGIFToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeGIF), nil -} - -// ExportAvif exports the image as AVIF to a buffer. -func (r *ImageRef) ExportAvif(params *AvifExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewAvifExportParams() - } - - buf, err := vipsSaveAVIFToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeAVIF), nil -} - -// ExportJp2k exports the image as JPEG2000 to a buffer. -func (r *ImageRef) ExportJp2k(params *Jp2kExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewJp2kExportParams() - } - - buf, err := vipsSaveJP2KToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeJP2K), nil -} - -// ExportJxl exports the image as JPEG XL to a buffer. -func (r *ImageRef) ExportJxl(params *JxlExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewJxlExportParams() - } - - buf, err := vipsSaveJxlToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeJXL), nil -} - -// ExportMagick exports the image as Format set in param to a buffer. -func (r *ImageRef) ExportMagick(params *MagickExportParams) ([]byte, *ImageMetadata, error) { - defer runtime.KeepAlive(r) - if params == nil { - params = NewMagickExportParams() - params.Format = "JPG" - } - - buf, err := vipsSaveMagickToBuffer(r.image, *params) - if err != nil { - return nil, nil, err - } - - return buf, r.newMetadata(ImageTypeMagick), nil -} - -// ToBytes writes the image to memory in VIPs format and returns the raw bytes, useful for storage. -func (r *ImageRef) ToBytes() ([]byte, error) { - defer runtime.KeepAlive(r) - var cSize C.size_t - cData := C.vips_image_write_to_memory(r.image, &cSize) - if cData == nil { - return nil, errors.New("failed to write image to memory") - } - defer C.free(cData) - - data := C.GoBytes(unsafe.Pointer(cData), C.int(cSize)) - return data, nil -} - -// ToImage converts a VIPs image to a golang image.Image object, useful for interoperability with other golang libraries. -// Deprecated: Use ToGoImage for a faster, direct conversion without encoding round-trip. -func (r *ImageRef) ToImage(params *ExportParams) (image.Image, error) { - imageBytes, _, err := r.ExportNative() - if err != nil { - return nil, err - } - - reader := bytes.NewReader(imageBytes) - img, _, err := image.Decode(reader) - if err != nil { - return nil, err - } - - return img, nil -} - -// ToGoImage converts a vips image directly to a Go image.Image without encoding. -// This is significantly faster than ToImage() which round-trips through JPEG/PNG. -// The resulting image will be in sRGB color space with 8-bit depth. -func (r *ImageRef) ToGoImage() (image.Image, error) { - defer runtime.KeepAlive(r) - - // Work on a copy to avoid mutating the receiver - tmp, err := vipsGenCopy(r.image, nil) - if err != nil { - return nil, err - } - defer clearImage(tmp) - - // Convert to sRGB if needed (keep B_W for grayscale) - interp := Interpretation(int(tmp.Type)) - if interp != InterpretationSRGB && interp != InterpretationBW { - out, err := vipsToColorSpace(tmp, InterpretationSRGB) - if err != nil { - return nil, err - } - clearImage(tmp) - tmp = out - } - - // Cast to uchar if needed - if BandFormat(int(tmp.BandFmt)) != BandFormatUchar { - out, err := vipsGenCast(tmp, BandFormatUchar, nil) - if err != nil { - return nil, err - } - clearImage(tmp) - tmp = out - } - - // Extract raw pixel data - var cSize C.size_t - cData := C.vips_image_write_to_memory(tmp, &cSize) - if cData == nil { - return nil, errors.New("failed to write image to memory") - } - defer C.free(cData) - - width := int(tmp.Xsize) - height := int(tmp.Ysize) - bands := int(tmp.Bands) - pixels := C.GoBytes(unsafe.Pointer(cData), C.int(cSize)) - - switch bands { - case 1: - img := image.NewGray(image.Rect(0, 0, width, height)) - copy(img.Pix, pixels) - return img, nil - case 2: - // Grayscale + alpha - img := image.NewNRGBA(image.Rect(0, 0, width, height)) - srcIdx := 0 - dstIdx := 0 - for srcIdx+1 < len(pixels) { - v := pixels[srcIdx] - img.Pix[dstIdx] = v - img.Pix[dstIdx+1] = v - img.Pix[dstIdx+2] = v - img.Pix[dstIdx+3] = pixels[srcIdx+1] - srcIdx += 2 - dstIdx += 4 - } - return img, nil - case 3: - // RGB, add opaque alpha - img := image.NewNRGBA(image.Rect(0, 0, width, height)) - srcIdx := 0 - dstIdx := 0 - for srcIdx+2 < len(pixels) { - img.Pix[dstIdx] = pixels[srcIdx] - img.Pix[dstIdx+1] = pixels[srcIdx+1] - img.Pix[dstIdx+2] = pixels[srcIdx+2] - img.Pix[dstIdx+3] = 255 - srcIdx += 3 - dstIdx += 4 - } - return img, nil - case 4: - img := image.NewNRGBA(image.Rect(0, 0, width, height)) - copy(img.Pix, pixels) - return img, nil - default: - return nil, fmt.Errorf("unsupported number of bands: %d", bands) - } -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_icc.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_icc.go deleted file mode 100644 index 4a6ff3a8d4..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_icc.go +++ /dev/null @@ -1,108 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "fmt" - "runtime" -) - -// GetICCProfile retrieves the ICC profile data (if any) from the image. -func (r *ImageRef) GetICCProfile() []byte { - defer runtime.KeepAlive(r) - bytes, _ := vipsGetICCProfile(r.image) - return bytes -} - -// RemoveICCProfile removes the ICC Profile information from the image. -// Typically, browsers and other software assume images without profile to be in the sRGB color space. -func (r *ImageRef) RemoveICCProfile() error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsRemoveICCProfile(out) - - r.setImage(out) - return nil -} - -// TransformICCProfileWithFallback transforms from the embedded ICC profile of the image to the ICC profile at the given path. -// The fallback ICC profile is used if the image does not have an embedded ICC profile. -func (r *ImageRef) TransformICCProfileWithFallback(targetProfilePath, fallbackProfilePath string) error { - defer runtime.KeepAlive(r) - if err := ensureLoadICCPath(&targetProfilePath); err != nil { - return err - } - if err := ensureLoadICCPath(&fallbackProfilePath); err != nil { - return err - } - - depth := 16 - if r.BandFormat() == BandFormatUchar || r.BandFormat() == BandFormatChar || r.BandFormat() == BandFormatNotSet { - depth = 8 - } - - out, err := vipsICCTransform(r.image, targetProfilePath, fallbackProfilePath, IntentPerceptual, depth, true) - if err != nil { - govipsLog("govips", LogLevelError, fmt.Sprintf("failed to do icc transform: %v", err.Error())) - return err - } - - r.setImage(out) - return nil -} - -// TransformICCProfile transforms from the embedded ICC profile of the image to the icc profile at the given path. -func (r *ImageRef) TransformICCProfile(outputProfilePath string) error { - return r.TransformICCProfileWithFallback(outputProfilePath, SRGBIEC6196621ICCProfilePath) -} - -// OptimizeICCProfile optimizes the ICC color profile of the image. -// For two color channel images, it sets a grayscale profile. -// For color images, it sets a CMYK or non-CMYK profile based on the image metadata. -func (r *ImageRef) OptimizeICCProfile() error { - defer runtime.KeepAlive(r) - inputProfile := r.determineInputICCProfile() - if !r.HasICCProfile() && (inputProfile == "") { - // No embedded ICC profile in the input image and no input profile determined, nothing to do. - return nil - } - - r.optimizedIccProfile = SRGBV2MicroICCProfilePath - if r.Bands() <= 2 { - r.optimizedIccProfile = SGrayV2MicroICCProfilePath - } - - if err := ensureLoadICCPath(&r.optimizedIccProfile); err != nil { - return err - } - - embedded := r.HasICCProfile() && (inputProfile == "") - - depth := 16 - if r.BandFormat() == BandFormatUchar || r.BandFormat() == BandFormatChar || r.BandFormat() == BandFormatNotSet { - depth = 8 - } - - out, err := vipsICCTransform(r.image, r.optimizedIccProfile, inputProfile, IntentPerceptual, depth, embedded) - if err != nil { - govipsLog("govips", LogLevelError, fmt.Sprintf("failed to do icc transform: %v", err.Error())) - return err - } - - r.setImage(out) - return nil -} - -func (r *ImageRef) determineInputICCProfile() (inputProfile string) { - if r.Interpretation() == InterpretationCMYK { - if !r.HasICCProfile() { - inputProfile = "cmyk" - } - } - return -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_metadata.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_metadata.go deleted file mode 100644 index 5b90bfc3b0..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_metadata.go +++ /dev/null @@ -1,338 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "runtime" - "strings" -) - -// Format returns the current format of the vips image. -func (r *ImageRef) Format() ImageType { - return r.format -} - -// OriginalFormat returns the original format of the image when loaded. -// In some cases the loaded image is converted on load, for example, a BMP is automatically converted to PNG -// This method returns the format of the original buffer, as opposed to Format() with will return the format of the -// currently held buffer content. -func (r *ImageRef) OriginalFormat() ImageType { - return r.originalFormat -} - -// Width returns the width of this image. -func (r *ImageRef) Width() int { - return int(r.image.Xsize) -} - -// Height returns the height of this image. -func (r *ImageRef) Height() int { - return int(r.image.Ysize) -} - -// Bands returns the number of bands for this image. -func (r *ImageRef) Bands() int { - return int(r.image.Bands) -} - -// HasProfile returns if the image has an ICC profile embedded. -func (r *ImageRef) HasProfile() bool { - defer runtime.KeepAlive(r) - return vipsHasICCProfile(r.image) -} - -// HasICCProfile checks whether the image has an ICC profile embedded. Alias to HasProfile -func (r *ImageRef) HasICCProfile() bool { - return r.HasProfile() -} - -// HasIPTC returns a boolean whether the image in question has IPTC data associated with it. -func (r *ImageRef) HasIPTC() bool { - defer runtime.KeepAlive(r) - return vipsHasIPTC(r.image) -} - -// HasAlpha returns if the image has an alpha layer. -func (r *ImageRef) HasAlpha() bool { - defer runtime.KeepAlive(r) - return vipsHasAlpha(r.image) -} - -// Orientation returns the orientation number as it appears in the EXIF, if present -func (r *ImageRef) Orientation() int { - defer runtime.KeepAlive(r) - return vipsGetMetaOrientation(r.image) -} - -// Deprecated: use Orientation() instead -func (r *ImageRef) GetOrientation() int { - return r.Orientation() -} - -// SetOrientation sets the orientation in the EXIF header of the associated image. -func (r *ImageRef) SetOrientation(orientation int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsSetMetaOrientation(out, orientation) - - r.setImage(out) - return nil -} - -// RemoveOrientation removes the EXIF orientation information of the image. -func (r *ImageRef) RemoveOrientation() error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsRemoveMetaOrientation(out) - - r.setImage(out) - return nil -} - -// ResX returns the X resolution -func (r *ImageRef) ResX() float64 { - return float64(r.image.Xres) -} - -// ResY returns the Y resolution -func (r *ImageRef) ResY() float64 { - return float64(r.image.Yres) -} - -// OffsetX returns the X offset -func (r *ImageRef) OffsetX() int { - return int(r.image.Xoffset) -} - -// OffsetY returns the Y offset -func (r *ImageRef) OffsetY() int { - return int(r.image.Yoffset) -} - -// BandFormat returns the current band format -func (r *ImageRef) BandFormat() BandFormat { - return BandFormat(int(r.image.BandFmt)) -} - -// Coding returns the image coding -func (r *ImageRef) Coding() Coding { - return Coding(int(r.image.Coding)) -} - -// Interpretation returns the current interpretation of the color space of the image. -func (r *ImageRef) Interpretation() Interpretation { - return Interpretation(int(r.image.Type)) -} - -// ColorSpace returns the interpretation of the current color space. Alias to Interpretation(). -func (r *ImageRef) ColorSpace() Interpretation { - return r.Interpretation() -} - -// IsColorSpaceSupported returns a boolean whether the image's color space is supported by libvips. -func (r *ImageRef) IsColorSpaceSupported() bool { - defer runtime.KeepAlive(r) - return vipsIsColorSpaceSupported(r.image) -} - -// Pages returns the number of pages in the Image -// For animated images this corresponds to the number of frames -func (r *ImageRef) Pages() int { - // libvips uses the same attribute (n_pages) to represent the number of pyramid layers in JP2K - // as we interpret the attribute as frames and JP2K does not support animation we override this with 1 - if r.format == ImageTypeJP2K { - return 1 - } - - defer runtime.KeepAlive(r) - return vipsGetImageNPages(r.image) -} - -// Deprecated: use Pages() instead -func (r *ImageRef) GetPages() int { - return r.Pages() -} - -// SetPages sets the number of pages in the Image -// For animated images this corresponds to the number of frames -func (r *ImageRef) SetPages(pages int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsSetImageNPages(out, pages) - - r.setImage(out) - return nil -} - -// PageHeight return the height of a single page -func (r *ImageRef) PageHeight() int { - defer runtime.KeepAlive(r) - return vipsGetPageHeight(r.image) -} - -// GetPageHeight return the height of a single page -// Deprecated use PageHeight() instead -func (r *ImageRef) GetPageHeight() int { - defer runtime.KeepAlive(r) - return vipsGetPageHeight(r.image) -} - -// SetPageHeight set the height of a page -// For animated images this is used when "unrolling" back to frames -func (r *ImageRef) SetPageHeight(height int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsSetPageHeight(out, height) - - r.setImage(out) - return nil -} - -// PageDelay get the page delay array for animation -func (r *ImageRef) PageDelay() ([]int, error) { - defer runtime.KeepAlive(r) - n := vipsGetImageNPages(r.image) - if n <= 1 { - // should not call if not multi page - return nil, nil - } - return vipsImageGetDelay(r.image, n) -} - -// SetPageDelay set the page delay array for animation -func (r *ImageRef) SetPageDelay(delay []int) error { - defer runtime.KeepAlive(r) - var data []C.int - for _, d := range delay { - data = append(data, C.int(d)) - } - return vipsImageSetDelay(r.image, data) -} - -// Loop returns the loop count for animated images. -// A value of 0 means infinite looping. -func (r *ImageRef) Loop() int { - defer runtime.KeepAlive(r) - return vipsImageGetLoop(r.image) -} - -// SetLoop sets the loop count for animated images. -// A value of 0 means infinite looping. -func (r *ImageRef) SetLoop(loop int) error { - defer runtime.KeepAlive(r) - vipsImageSetLoop(r.image, loop) - return nil -} - -// Background get the background of image. -func (r *ImageRef) Background() ([]float64, error) { - defer runtime.KeepAlive(r) - out, err := vipsImageGetBackground(r.image) - if err != nil { - return nil, err - } - return out, nil -} - -func (r *ImageRef) ImageFields() []string { - return r.GetFields() -} - -func (r *ImageRef) GetFields() []string { - defer runtime.KeepAlive(r) - return vipsImageGetFields(r.image) -} - -func (r *ImageRef) SetBlob(name string, data []byte) { - defer runtime.KeepAlive(r) - vipsImageSetBlob(r.image, name, data) -} - -func (r *ImageRef) GetBlob(name string) []byte { - defer runtime.KeepAlive(r) - return vipsImageGetBlob(r.image, name) -} - -func (r *ImageRef) SetDouble(name string, f float64) { - defer runtime.KeepAlive(r) - vipsImageSetDouble(r.image, name, f) -} - -func (r *ImageRef) GetDouble(name string) float64 { - defer runtime.KeepAlive(r) - return vipsImageGetDouble(r.image, name) -} - -func (r *ImageRef) SetInt(name string, i int) { - defer runtime.KeepAlive(r) - vipsImageSetInt(r.image, name, i) -} - -func (r *ImageRef) GetInt(name string) int { - defer runtime.KeepAlive(r) - return vipsImageGetInt(r.image, name) -} - -func (r *ImageRef) SetString(name string, str string) { - defer runtime.KeepAlive(r) - vipsImageSetString(r.image, name, str) -} - -func (r *ImageRef) GetString(name string) string { - defer runtime.KeepAlive(r) - return vipsImageGetString(r.image, name) -} - -func (r *ImageRef) GetAsString(name string) string { - defer runtime.KeepAlive(r) - return vipsImageGetAsString(r.image, name) -} - -func (r *ImageRef) HasExif() bool { - for _, field := range r.ImageFields() { - if strings.HasPrefix(field, "exif-") { - return true - } - } - - return false -} - -func (r *ImageRef) GetExif() map[string]string { - defer runtime.KeepAlive(r) - return vipsImageGetExifData(r.image) -} - -// RemoveMetadata removes the EXIF metadata from the image. -// N.B. this function won't remove the ICC profile, orientation and pages metadata -// because govips needs it to correctly display the image. -func (r *ImageRef) RemoveMetadata(keep ...string) error { - defer runtime.KeepAlive(r) - out, err := vipsGenCopy(r.image, nil) - if err != nil { - return err - } - - vipsRemoveMetadata(out, keep...) - - r.setImage(out) - - return nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_pixel.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_pixel.go deleted file mode 100644 index db65d86355..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_pixel.go +++ /dev/null @@ -1,393 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "errors" - "runtime" -) - -// GaussianBlur blurs the image -// add support minAmpl -func (r *ImageRef) GaussianBlur(sigmas ...float64) error { - defer runtime.KeepAlive(r) - var ( - sigma = sigmas[0] - minAmpl = GaussBlurDefaultMinAMpl - ) - if len(sigmas) >= 2 { - minAmpl = sigmas[1] - } - out, err := vipsGenGaussblur(r.image, sigma, &GaussblurOptions{MinAmpl: &minAmpl}) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Sharpen sharpens the image -// sigma: sigma of the gaussian -// x1: flat/jaggy threshold -// m2: slope for jaggy areas -func (r *ImageRef) Sharpen(sigma float64, x1 float64, m2 float64) error { - defer runtime.KeepAlive(r) - out, err := vipsGenSharpen(r.image, &SharpenOptions{Sigma: &sigma, X1: &x1, M2: &m2}) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Apply Sobel edge detector to the image. -func (r *ImageRef) Sobel() error { - defer runtime.KeepAlive(r) - out, err := vipsGenSobel(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Rank does rank filtering on an image. A window of size width by height is passed over the image. -// At each position, the pixels inside the window are sorted into ascending order and the pixel at position -// index is output. index numbers from 0. -func (r *ImageRef) Rank(width int, height int, index int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenRank(r.image, width, height, index) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Mapim resamples an image using index to look up pixels -func (r *ImageRef) Mapim(index *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(index) - out, err := vipsGenMapim(r.image, index.image, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Maplut maps an image through another image acting as a LUT (Look Up Table) -func (r *ImageRef) Maplut(lut *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(lut) - out, err := vipsGenMaplut(r.image, lut.image, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// ExtractBand extracts one or more bands out of the image (replacing the associated ImageRef) -func (r *ImageRef) ExtractBand(band int, num int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenExtractBand(r.image, band, &ExtractBandOptions{N: &num}) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// ExtractBandToImage extracts one or more bands out of the image to a new image -func (r *ImageRef) ExtractBandToImage(band int, num int) (*ImageRef, error) { - defer runtime.KeepAlive(r) - out, err := vipsGenExtractBand(r.image, band, &ExtractBandOptions{N: &num}) - if err != nil { - return nil, err - } - return newImageRef(out, ImageTypeUnknown, ImageTypeUnknown, nil), nil -} - -// BandJoin joins a set of images together, bandwise. -func (r *ImageRef) BandJoin(images ...*ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(images) - vipsImages := []*C.VipsImage{r.image} - for _, vipsImage := range images { - vipsImages = append(vipsImages, vipsImage.image) - } - - out, err := vipsGenBandjoin(vipsImages) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// BandSplit split an n-band image into n separate images.. -func (r *ImageRef) BandSplit() ([]*ImageRef, error) { - defer runtime.KeepAlive(r) - var out []*ImageRef - n := 1 - for i := 0; i < r.Bands(); i++ { - img, err := vipsGenExtractBand(r.image, i, &ExtractBandOptions{N: &n}) - if err != nil { - return out, err - } - out = append(out, &ImageRef{image: img}) - } - return out, nil -} - -// BandJoinConst appends a set of constant bands to an image. -func (r *ImageRef) BandJoinConst(constants []float64) error { - defer runtime.KeepAlive(r) - if len(constants) == 0 { - return errors.New("BandJoinConst: empty constants slice") - } - out, err := vipsGenBandjoinConst(r.image, constants) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// AddAlpha adds an alpha channel to the associated image. -func (r *ImageRef) AddAlpha() error { - defer runtime.KeepAlive(r) - if vipsHasAlpha(r.image) { - return nil - } - - out, err := vipsAddAlpha(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// PremultiplyAlpha premultiplies the alpha channel. -// See https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-premultiply -func (r *ImageRef) PremultiplyAlpha() error { - defer runtime.KeepAlive(r) - if r.preMultiplication != nil || !vipsHasAlpha(r.image) { - return nil - } - - band := r.BandFormat() - - out, err := vipsGenPremultiply(r.image, nil) - if err != nil { - return err - } - r.preMultiplication = &PreMultiplicationState{ - bandFormat: band, - } - r.setImage(out) - return nil -} - -// UnpremultiplyAlpha unpremultiplies any alpha channel. -// See https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-unpremultiply -func (r *ImageRef) UnpremultiplyAlpha() error { - defer runtime.KeepAlive(r) - if r.preMultiplication == nil { - return nil - } - - unpremultiplied, err := vipsGenUnpremultiply(r.image, nil) - if err != nil { - return err - } - defer clearImage(unpremultiplied) - - out, err := vipsGenCast(unpremultiplied, r.preMultiplication.bandFormat, nil) - if err != nil { - return err - } - - r.preMultiplication = nil - r.setImage(out) - return nil -} - -// Add calculates a sum of the image + addend and stores it back in the image -func (r *ImageRef) Add(addend *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(addend) - out, err := vipsGenAdd(r.image, addend.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Multiply calculates the product of the image * multiplier and stores it back in the image -func (r *ImageRef) Multiply(multiplier *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(multiplier) - out, err := vipsGenMultiply(r.image, multiplier.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Divide calculates the product of the image / denominator and stores it back in the image -func (r *ImageRef) Divide(denominator *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(denominator) - out, err := vipsGenDivide(r.image, denominator.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Average finds the average value in an image -func (r *ImageRef) Average() (float64, error) { - defer runtime.KeepAlive(r) - out, err := vipsGenAvg(r.image) - if err != nil { - return 0, err - } - return out, nil -} - -// FindTrim returns the bounding box of the non-border part of the image -// Returned values are left, top, width, height -func (r *ImageRef) FindTrim(threshold float64, backgroundColor *Color) (int, int, int, int, error) { - defer runtime.KeepAlive(r) - return vipsFindTrim(r.image, threshold, backgroundColor) -} - -// GetPoint reads a single pixel on an image. -// The pixel values are returned in a slice with one element per band. -func (r *ImageRef) GetPoint(x int, y int) ([]float64, error) { - defer runtime.KeepAlive(r) - return vipsGetPoint(r.image, r.Bands(), x, y) -} - -// Stats find many image statistics in a single pass through the data. Image is changed into a one-band -// `BandFormatDouble` image of at least 10 columns by n + 1 (where n is number of bands in image in) -// rows. Columns are statistics, and are, in order: minimum, maximum, sum, sum of squares, mean, -// standard deviation, x coordinate of minimum, y coordinate of minimum, x coordinate of maximum, -// y coordinate of maximum. -// -// Row 0 has statistics for all bands together, row 1 has stats for band 1, and so on. -// -// If there is more than one maxima or minima, one of them will be chosen at random. -func (r *ImageRef) Stats() error { - defer runtime.KeepAlive(r) - out, err := vipsGenStats(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// HistogramFind find the histogram the image. -// Find the histogram for all bands (producing a one-band histogram). -// char and uchar images are cast to uchar before histogramming, all other image types are cast to ushort. -func (r *ImageRef) HistogramFind() error { - defer runtime.KeepAlive(r) - out, err := vipsGenHistFind(r.image, nil) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// HistogramCumulative form cumulative histogram. -func (r *ImageRef) HistogramCumulative() error { - defer runtime.KeepAlive(r) - out, err := vipsGenHistCum(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// HistogramNormalise -// The maximum of each band becomes equal to the maximum index, so for example the max for a uchar -// image becomes 255. Normalise each band separately. -func (r *ImageRef) HistogramNormalise() error { - defer runtime.KeepAlive(r) - out, err := vipsGenHistNorm(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// HistogramEntropy estimate image entropy from a histogram. Entropy is calculated as: -// `-sum(p * log2(p))` -// where p is histogram-value / sum-of-histogram-values. -func (r *ImageRef) HistogramEntropy() (float64, error) { - defer runtime.KeepAlive(r) - return vipsGenHistEntropy(r.image) -} - -// DrawRect draws an (optionally filled) rectangle with a single colour -func (r *ImageRef) DrawRect(ink ColorRGBA, left int, top int, width int, height int, fill bool) error { - defer runtime.KeepAlive(r) - err := vipsDrawRect(r.image, ink, left, top, width, height, fill) - if err != nil { - return err - } - return nil -} - -// Subtract calculate subtract operation between two images. -func (r *ImageRef) Subtract(in2 *ImageRef) error { - defer runtime.KeepAlive(r) - defer runtime.KeepAlive(in2) - out, err := vipsGenSubtract(r.image, in2.image) - if err != nil { - return err - } - - r.setImage(out) - return nil -} - -// Abs calculate abs operation. -func (r *ImageRef) Abs() error { - defer runtime.KeepAlive(r) - out, err := vipsGenAbs(r.image) - if err != nil { - return err - } - - r.setImage(out) - return nil -} - -// Project calculate project operation. -func (r *ImageRef) Project() (*ImageRef, *ImageRef, error) { - defer runtime.KeepAlive(r) - col, row, err := vipsGenProject(r.image) - if err != nil { - return nil, nil, err - } - - return newImageRef(col, r.format, r.originalFormat, nil), newImageRef(row, r.format, r.originalFormat, nil), nil -} - -// Min finds the minimum value in an image. -func (r *ImageRef) Min() (float64, int, int, error) { - defer runtime.KeepAlive(r) - return vipsMin(r.image) -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/image_transform.go b/vendor/github.com/davidbyttow/govips/v2/vips/image_transform.go deleted file mode 100644 index 9975b4627c..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/image_transform.go +++ /dev/null @@ -1,458 +0,0 @@ -package vips - -// #include "image.h" -import "C" - -import ( - "errors" - "math" - "runtime" - "unsafe" -) - -// GetRotationAngleFromExif returns the angle which the image is currently rotated in. -// First returned value is the angle and second is a boolean indicating whether image is flipped. -// This is based on the EXIF orientation tag standard. -// If no proper orientation number is provided, the picture will be assumed to be upright. -func GetRotationAngleFromExif(orientation int) (Angle, bool) { - switch orientation { - case 0, 1, 2: - return Angle0, orientation == 2 - case 3, 4: - return Angle180, orientation == 4 - case 5, 8: - return Angle90, orientation == 5 - case 6, 7: - return Angle270, orientation == 7 - } - - return Angle0, false -} - -// AutoRotate rotates the image upright based on the EXIF Orientation tag, -// including the mirrored orientations (2, 4, 5 and 7), which libvips -// handles with a flip since 8.10. -// It also resets the orientation information in the EXIF tag to be 1 (i.e. upright). -// N.B. due to the HEIF image standard, HEIF images are always autorotated by default on load. -// Thus, calling AutoRotate for HEIF images is not needed. -// todo: use https://www.libvips.org/API/current/libvips-conversion.html#vips-autorot-remove-angle -func (r *ImageRef) AutoRotate() error { - defer runtime.KeepAlive(r) - out, _, _, err := vipsGenAutorot(r.image) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// ExtractArea crops the image to a specified area -func (r *ImageRef) ExtractArea(left, top, width, height int) error { - defer runtime.KeepAlive(r) - if r.Height() > r.PageHeight() { - // use animated extract area if more than 1 pages loaded - out, err := vipsExtractAreaMultiPage(r.image, left, top, width, height) - if err != nil { - return err - } - r.setImage(out) - } else { - out, err := vipsExtractArea(r.image, left, top, width, height) - if err != nil { - return err - } - r.setImage(out) - } - return nil -} - -// Resize resizes the image based on the scale, maintaining aspect ratio -func (r *ImageRef) Resize(scale float64, kernel Kernel) error { - return r.ResizeWithVScale(scale, -1, kernel) -} - -// ResizeWithVScale resizes the image with both horizontal and vertical scaling. -// The parameters are the scaling factors. -func (r *ImageRef) ResizeWithVScale(hScale, vScale float64, kernel Kernel) error { - defer runtime.KeepAlive(r) - if err := r.PremultiplyAlpha(); err != nil { - return err - } - - pages := r.loadedPages() - newPageHeight := 0 - if pages > 1 { - scale := hScale - if vScale > 0 { - scale = vScale - } - newPageHeight = int(math.Round(float64(r.PageHeight()) * scale)) - if newPageHeight < 1 { - newPageHeight = 1 - } - // libvips resizes the stacked frames as one strip, so rounding the - // strip and the page height separately can leave the strip a few - // rows short of pages*newPageHeight (#350, #554). When that happens, - // pick the vertical scale that makes the strip height exact, as - // vips_thumbnail does. Output is unchanged when the rounding agrees. - height := r.Height() - if int(math.Round(float64(height)*scale)) != pages*newPageHeight { - vScale = float64(pages*newPageHeight) / float64(height) - } - } - - out, err := vipsResizeWithVScale(r.image, hScale, vScale, kernel) - if err != nil { - return err - } - r.setImage(out) - - if pages > 1 { - if err := r.SetPageHeight(newPageHeight); err != nil { - return err - } - } - - return r.UnpremultiplyAlpha() -} - -// loadedPages is the number of pages stacked in the image. Pages() reports -// the page count of the file, which is larger when only some were loaded. -func (r *ImageRef) loadedPages() int { - pageHeight := r.PageHeight() - if pageHeight <= 0 { - return 1 - } - return r.Height() / pageHeight -} - -// Thumbnail resizes the image to the given width and height. -// crop decides algorithm vips uses to shrink and crop to fill target, -func (r *ImageRef) Thumbnail(width, height int, crop Interesting) error { - defer runtime.KeepAlive(r) - out, err := vipsThumbnail(r.image, width, height, crop, SizeBoth) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// ThumbnailWithSize resizes the image to the given width and height. -// crop decides algorithm vips uses to shrink and crop to fill target, -// size controls upsize, downsize, both or force -func (r *ImageRef) ThumbnailWithSize(width, height int, crop Interesting, size Size) error { - defer runtime.KeepAlive(r) - out, err := vipsThumbnail(r.image, width, height, crop, size) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Embed embeds the given picture in a new one, i.e. the opposite of ExtractArea -func (r *ImageRef) Embed(left, top, width, height int, extend ExtendStrategy) error { - defer runtime.KeepAlive(r) - if r.Height() > r.PageHeight() { - out, err := vipsEmbedMultiPage(r.image, left, top, width, height, extend) - if err != nil { - return err - } - r.setImage(out) - } else { - out, err := vipsEmbed(r.image, left, top, width, height, extend) - if err != nil { - return err - } - r.setImage(out) - } - return nil -} - -// EmbedBackground embeds the given picture with a background color. -// For greyscale images (1-2 bands) the R value is used as the grey level. -func (r *ImageRef) EmbedBackground(left, top, width, height int, backgroundColor *Color) error { - defer runtime.KeepAlive(r) - c := &ColorRGBA{ - R: backgroundColor.R, - G: backgroundColor.G, - B: backgroundColor.B, - A: 255, - } - if r.Height() > r.PageHeight() { - out, err := vipsEmbedMultiPageBackground(r.image, left, top, width, height, c) - if err != nil { - return err - } - r.setImage(out) - } else { - out, err := vipsEmbedBackground(r.image, left, top, width, height, c) - if err != nil { - return err - } - r.setImage(out) - } - return nil -} - -// EmbedBackgroundRGBA embeds the given picture with a background rgba color. -// For greyscale images the background is built from R and A only: -// 1 band uses {R}, 2 bands (grey+alpha) use {R, A}. -func (r *ImageRef) EmbedBackgroundRGBA(left, top, width, height int, backgroundColor *ColorRGBA) error { - defer runtime.KeepAlive(r) - if r.Height() > r.PageHeight() { - out, err := vipsEmbedMultiPageBackground(r.image, left, top, width, height, backgroundColor) - if err != nil { - return err - } - r.setImage(out) - } else { - out, err := vipsEmbedBackground(r.image, left, top, width, height, backgroundColor) - if err != nil { - return err - } - r.setImage(out) - } - return nil -} - -// Zoom zooms the image by repeating pixels (fast nearest-neighbour) -func (r *ImageRef) Zoom(xFactor int, yFactor int) error { - defer runtime.KeepAlive(r) - pages := r.loadedPages() - pageHeight := r.PageHeight() - out, err := vipsGenZoom(r.image, xFactor, yFactor) - if err != nil { - return err - } - r.setImage(out) - if pages > 1 { - // Zooming the strip zooms every frame; only the page height is stale. - return r.SetPageHeight(pageHeight * yFactor) - } - return nil -} - -func (r *ImageRef) Gravity(gravity Gravity, width int, height int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenGravity(r.image, gravity, width, height, nil) - if err != nil { - return err - } - - r.setImage(out) - return nil -} - -// Flip flips the image either horizontally or vertically based on the parameter -func (r *ImageRef) Flip(direction Direction) error { - defer runtime.KeepAlive(r) - var out *C.VipsImage - var err error - if direction == DirectionVertical && r.loadedPages() > 1 { - // Flipping the strip would reverse the frame order. - out, err = vipsMapPages(r.image, func(page *C.VipsImage) (*C.VipsImage, error) { - return vipsFlip(page, direction) - }) - } else { - out, err = vipsFlip(r.image, direction) - } - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Recomb recombines the image bands using the matrix provided -func (r *ImageRef) Recomb(matrix [][]float64) error { - defer runtime.KeepAlive(r) - numBands := r.Bands() - // Ensure the provided matrix is 3x3 - if len(matrix) != 3 || len(matrix[0]) != 3 || len(matrix[1]) != 3 || len(matrix[2]) != 3 { - return errors.New("Invalid recombination matrix") - } - // If the image is RGBA, expand the matrix to 4x4 - if numBands == 4 { - matrix = append(matrix, []float64{0, 0, 0, 1}) - for i := 0; i < 3; i++ { - matrix[i] = append(matrix[i], 0) - } - } else if numBands != 3 { - return errors.New("Unsupported number of bands") - } - - // Flatten the matrix - matrixValues := make([]float64, 0, numBands*numBands) - for _, row := range matrix { - for _, value := range row { - matrixValues = append(matrixValues, value) - } - } - - // Convert the Go slice to a C array and get its size - matrixPtr := unsafe.Pointer(&matrixValues[0]) - matrixSize := C.size_t(len(matrixValues) * 8) // 8 bytes for each float64 - - // Create a VipsImage from the matrix in memory - matrixImage := C.vips_image_new_from_memory(matrixPtr, matrixSize, C.int(numBands), C.int(numBands), 1, C.VIPS_FORMAT_DOUBLE) - defer clearImage(matrixImage) - - if matrixImage == nil { - return handleVipsError() - } - - // Recombine the image using the matrix - out, err := vipsGenRecomb(r.image, matrixImage) - runtime.KeepAlive(matrixValues) - if err != nil { - return err - } - - r.setImage(out) - return nil -} - -// Rotate rotates the image by multiples of 90 degrees. To rotate by arbitrary angles use Similarity. -func (r *ImageRef) Rotate(angle Angle) error { - defer runtime.KeepAlive(r) - width := r.Width() - pages := r.loadedPages() - - if pages > 1 && angle == Angle180 { - // Rotating the strip would reverse the frame order. - out, err := vipsMapPages(r.image, func(page *C.VipsImage) (*C.VipsImage, error) { - return vipsGenRot(page, angle) - }) - if err != nil { - return err - } - r.setImage(out) - return nil - } - - if pages > 1 && (angle == Angle90 || angle == Angle270) { - if angle == Angle270 { - if err := r.Flip(DirectionHorizontal); err != nil { - return err - } - } - - if err := r.Grid(r.PageHeight(), pages, 1); err != nil { - return err - } - - if angle == Angle270 { - if err := r.Flip(DirectionHorizontal); err != nil { - return err - } - } - - } - - out, err := vipsGenRot(r.image, angle) - if err != nil { - return err - } - r.setImage(out) - - if pages > 1 && (angle == Angle90 || angle == Angle270) { - if err := r.SetPageHeight(width); err != nil { - return err - } - } - return nil -} - -// Similarity lets you scale, offset and rotate images by arbitrary angles in a single operation while defining the -// color of new background pixels. If the input image has no alpha channel, the alpha on `backgroundColor` will be -// ignored. You can add an alpha channel to an image with `BandJoinConst` (e.g. `img.BandJoinConst([]float64{255})`) or -// AddAlpha. -func (r *ImageRef) Similarity(scale float64, angle float64, backgroundColor *ColorRGBA, - idx float64, idy float64, odx float64, ody float64) error { - defer runtime.KeepAlive(r) - out, err := vipsSimilarity(r.image, scale, angle, backgroundColor, idx, idy, odx, ody) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Grid tiles the image pages into a matrix across*down -func (r *ImageRef) Grid(tileHeight, across, down int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenGrid(r.image, tileHeight, across, down) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// SmartCrop will crop the image based on interesting factor -func (r *ImageRef) SmartCrop(width int, height int, interesting Interesting) error { - defer runtime.KeepAlive(r) - out, err := vipsSmartCrop(r.image, width, height, interesting) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Crop will crop the image based on coordinate and box size -func (r *ImageRef) Crop(left int, top int, width int, height int) error { - defer runtime.KeepAlive(r) - out, err := vipsCrop(r.image, left, top, width, height) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Label overlays a label on top of the image -func (r *ImageRef) Label(labelParams *LabelParams) error { - defer runtime.KeepAlive(r) - out, err := labelImage(r.image, labelParams) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Replicate repeats an image many times across and down -func (r *ImageRef) Replicate(across int, down int) error { - defer runtime.KeepAlive(r) - out, err := vipsGenReplicate(r.image, across, down) - if err != nil { - return err - } - r.setImage(out) - return nil -} - -// Pixelate applies a simple pixelate filter to the image -func Pixelate(imageRef *ImageRef, factor float64) (err error) { - if factor < 1 { - return errors.New("factor must be greater then 1") - } - - width := imageRef.Width() - height := imageRef.Height() - - if err = imageRef.Resize(1/factor, KernelAuto); err != nil { - return - } - - hScale := float64(width) / float64(imageRef.Width()) - vScale := float64(height) / float64(imageRef.Height()) - if err = imageRef.ResizeWithVScale(hScale, vScale, KernelNearest); err != nil { - return - } - - return -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/interpolate.go b/vendor/github.com/davidbyttow/govips/v2/vips/interpolate.go deleted file mode 100644 index 4854f2346a..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/interpolate.go +++ /dev/null @@ -1,20 +0,0 @@ -package vips - -// #include -import "C" - -import "unsafe" - -// NewInterpolate creates a VipsInterpolate from a name string. -// Common names: "nearest", "bilinear", "bicubic", "nohalo", "vsqbs", "lbb". -// The caller should call g_object_unref on the result when done, or pass it -// to a generated operation (which does not take ownership). -func NewInterpolate(name string) (*C.VipsInterpolate, error) { - cName := C.CString(name) - defer C.free(unsafe.Pointer(cName)) - interp := C.vips_interpolate_new(cName) - if interp == nil { - return nil, handleVipsError() - } - return interp, nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/lang.go b/vendor/github.com/davidbyttow/govips/v2/vips/lang.go deleted file mode 100644 index 56ce86a3b0..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/lang.go +++ /dev/null @@ -1,62 +0,0 @@ -package vips - -// #include -// #include -import "C" - -import ( - "reflect" - "unsafe" -) - -func freeCString(s *C.char) { - C.free(unsafe.Pointer(s)) -} - -func gFreePointer(ref unsafe.Pointer) { - C.g_free(C.gpointer(ref)) -} - -func boolToInt(b bool) int { - if b { - return 1 - } - return 0 -} - -func toGboolean(b bool) C.gboolean { - if b { - return C.gboolean(1) - } - return C.gboolean(0) -} - -func fromGboolean(b C.gboolean) bool { - return b != 0 -} - -func fromCArrayInt(out *C.int, n int) []int { - var result = make([]int, n) - var data []C.int - sh := (*reflect.SliceHeader)(unsafe.Pointer(&data)) - sh.Data = uintptr(unsafe.Pointer(out)) - sh.Len = n - sh.Cap = n - for i := range data { - result[i] = int(data[i]) - } - return result -} - -func fromCArrayDouble(out *C.double, n int) []float64 { - if out == nil || n <= 0 { - return nil - } - - data := make([]float64, n) - for i := 0; i < n; i++ { - data[i] = float64(*(*C.double)(unsafe.Pointer(uintptr(unsafe.Pointer(out)) + uintptr(i)*unsafe.Sizeof(C.double(0))))) - } - - return data -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/lang.h b/vendor/github.com/davidbyttow/govips/v2/vips/lang.h deleted file mode 100644 index 089d58e795..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/lang.h +++ /dev/null @@ -1,2 +0,0 @@ -#include -#include diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/logging.go b/vendor/github.com/davidbyttow/govips/v2/vips/logging.go deleted file mode 100644 index 5053d0162f..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/logging.go +++ /dev/null @@ -1,98 +0,0 @@ -package vips - -// #include -import "C" -import ( - "log" -) - -// LogLevel is the enum controlling logging message verbosity. -type LogLevel int - -// The logging verbosity levels classify and filter logging messages. -// From most to least verbose, they are debug, info, message, warning, critical and error. -const ( - LogLevelError LogLevel = C.G_LOG_LEVEL_ERROR - LogLevelCritical LogLevel = C.G_LOG_LEVEL_CRITICAL - LogLevelWarning LogLevel = C.G_LOG_LEVEL_WARNING - LogLevelMessage LogLevel = C.G_LOG_LEVEL_MESSAGE - LogLevelInfo LogLevel = C.G_LOG_LEVEL_INFO - LogLevelDebug LogLevel = C.G_LOG_LEVEL_DEBUG -) - -// Three global variables which keep state of the current logging handler -// function, desired verbosity for logging and whether defaults have been -// overridden. Set by LoggingSettings() -var ( - currentLoggingHandlerFunction LoggingHandlerFunction - currentLoggingVerbosity LogLevel - currentLoggingOverridden bool -) - -// govipsLoggingHandler is the private bridge function exported to the C library -// and called by glib and libvips for each logging message. It will call govipsLog -// which in turn will filter based on verbosity and direct the messages to the -// currently chosen LoggingHandlerFunction. -// -//export govipsLoggingHandler -func govipsLoggingHandler(messageDomain *C.char, messageLevel C.int, message *C.char) { - govipsLog(C.GoString(messageDomain), LogLevel(messageLevel), C.GoString(message)) -} - -// LoggingHandlerFunction is a function which will be called for each log message. -// By default, govips sends logging messages to os.Stderr. If you want to log elsewhere -// such as to a file or to a state variable which you inspect yourself, define a new -// logging handler function and set it via LoggingSettings(). -type LoggingHandlerFunction func(messageDomain string, messageLevel LogLevel, message string) - -// LoggingSettings sets the logging handler and logging verbosity for govips. -// The handler function is the function which will be called for each log message. -// You can define one yourself to log somewhere else besides the default (stderr). -// Use nil as handler to use standard logging handler. -// Verbosity is the minimum logLevel you want to log. Default is logLevelInfo -// due to backwards compatibility but it's quite verbose for a library. -// Suggest setting it to at least logLevelWarning. Use logLevelDebug for debugging. -func LoggingSettings(handler LoggingHandlerFunction, verbosity LogLevel) { - currentLoggingOverridden = true - govipsLoggingSettings(handler, verbosity) -} - -func govipsLoggingSettings(handler LoggingHandlerFunction, verbosity LogLevel) { - if handler == nil { - currentLoggingHandlerFunction = defaultLoggingHandlerFunction - } else { - currentLoggingHandlerFunction = handler - } - - currentLoggingVerbosity = verbosity - // TODO turn on debugging in libvips and redirect to handler when setting verbosity to debug - // This way debugging information would go to the same channel as all other logging -} - -func defaultLoggingHandlerFunction(messageDomain string, messageLevel LogLevel, message string) { - var messageLevelDescription string - switch messageLevel { - case LogLevelError: - messageLevelDescription = "error" - case LogLevelCritical: - messageLevelDescription = "critical" - case LogLevelWarning: - messageLevelDescription = "warning" - case LogLevelMessage: - messageLevelDescription = "message" - case LogLevelInfo: - messageLevelDescription = "info" - case LogLevelDebug: - messageLevelDescription = "debug" - } - - log.Printf("[%v.%v] %v", messageDomain, messageLevelDescription, message) -} - -// govipsLog is the default function used to log debug or error messages internally in govips. -// It's used by all govips functionality directly, as well as by glib and libvips via the C bridge. -func govipsLog(messageDomain string, messageLevel LogLevel, message string) { - if messageLevel <= currentLoggingVerbosity { - currentLoggingHandlerFunction(messageDomain, messageLevel, message) - } -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/math.go b/vendor/github.com/davidbyttow/govips/v2/vips/math.go deleted file mode 100644 index b4e1bff344..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/math.go +++ /dev/null @@ -1,57 +0,0 @@ -package vips - -import "math" - -// Scalar is the basic scalar measurement of an image's height, width or offset coordinate. -type Scalar struct { - Value float64 - Relative bool -} - -// ValueOf takes a floating point value and returns a corresponding Scalar struct -func ValueOf(value float64) Scalar { - return Scalar{value, false} -} - -// IsZero checks whether the associated Scalar's value is zero. -func (s *Scalar) IsZero() bool { - return s.Value == 0 && !s.Relative -} - -// SetInt sets an integer value for the associated Scalar. -func (s *Scalar) SetInt(value int) { - s.Set(float64(value)) -} - -// Set sets a float value for the associated Scalar. -func (s *Scalar) Set(value float64) { - s.Value = value - s.Relative = false -} - -// SetScale sets a float value for the associated Scalar and makes it relative. -func (s *Scalar) SetScale(f float64) { - s.Value = f - s.Relative = true -} - -// Get returns the value of the scalar. Either absolute, or if relative, multiplied by the base given as parameter. -func (s *Scalar) Get(base int) float64 { - if s.Relative { - return s.Value * float64(base) - } - return s.Value -} - -// GetRounded returns the value of the associated Scalar, rounded to the nearest integer, if absolute. -// If the Scalar is relative, it will be multiplied by the supplied base parameter. -func (s *Scalar) GetRounded(base int) int { - return roundFloat(s.Get(base)) -} - -func roundFloat(f float64) int { - if f < 0 { - return int(math.Ceil(f - 0.5)) - } - return int(math.Floor(f + 0.5)) -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/operations.c b/vendor/github.com/davidbyttow/govips/v2/vips/operations.c deleted file mode 100644 index 449e15d382..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/operations.c +++ /dev/null @@ -1,505 +0,0 @@ -// operations.c - Hand-written C bridge functions for libvips operations - -#include "lang.h" -#include "operations.h" - -#include - -static int is_16bit(VipsInterpretation interpretation); - -// Arithmetic - -int find_trim(VipsImage *in, int *left, int *top, int *width, int *height, - double threshold, double r, double g, double b) { - - if (in->Type == VIPS_INTERPRETATION_RGB16 || in->Type == VIPS_INTERPRETATION_GREY16) { - r = 65535 * r / 255; - g = 65535 * g / 255; - b = 65535 * b / 255; - } - - double background[3] = {r, g, b}; - VipsArrayDouble *vipsBackground = vips_array_double_new(background, 3); - - int code = vips_find_trim(in, left, top, width, height, "threshold", threshold, "background", vipsBackground, NULL); - - vips_area_unref(VIPS_AREA(vipsBackground)); - return code; -} - -int getpoint(VipsImage *in, double **vector, int n, int x, int y) { - return vips_getpoint(in, vector, &n, x, y, NULL); -} - -int minOp(VipsImage *in, double *out, int *x, int *y, int size) { - return vips_min(in, out, "x", x, "y", y, "size", size, NULL); -} - -// Color - -int is_colorspace_supported(VipsImage *in) { - return vips_colourspace_issupported(in) ? 1 : 0; -} - -int to_colorspace(VipsImage *in, VipsImage **out, VipsInterpretation space) { - return vips_colourspace(in, out, space, NULL); -} - -// https://libvips.github.io/libvips/API/8.6/libvips-colour.html#vips-icc-transform -int icc_transform(VipsImage *in, VipsImage **out, const char *output_profile, const char *input_profile, VipsIntent intent, - int depth, gboolean embedded) { - return vips_icc_transform( - in, out, output_profile, - "input_profile", input_profile ? input_profile : "none", - "intent", intent, - "depth", depth ? depth : 8, - "embedded", embedded, - NULL); -} - -// Conversion - -// background_for_bands fills vec with a background vector sized to the -// image's band count and returns the element count; libvips rejects -// vectors longer than the band count (e.g. "linear: vector must have 1 -// or 2 elements" for greyscale images). Greyscale images take the R -// value as the grey level: 1 band -> {r}, 2 bands -> {r, a}. -static int background_for_bands(VipsImage *in, double vec[4], double r, - double g, double b, double a) { - switch (in->Bands) { - case 1: - vec[0] = r; - return 1; - case 2: - vec[0] = r; - vec[1] = a; - return 2; - case 3: - vec[0] = r; - vec[1] = g; - vec[2] = b; - return 3; - default: - vec[0] = r; - vec[1] = g; - vec[2] = b; - vec[3] = a; - return 4; - } -} - -int embed_image(VipsImage *in, VipsImage **out, int left, int top, int width, - int height, int extend) { - return vips_embed(in, out, left, top, width, height, "extend", extend, NULL); -} - -int embed_image_background(VipsImage *in, VipsImage **out, int left, int top, int width, - int height, double r, double g, double b, double a) { - - double background[4]; - int n = background_for_bands(in, background, r, g, b, a); - VipsArrayDouble *vipsBackground = vips_array_double_new(background, n); - - int code = vips_embed(in, out, left, top, width, height, - "extend", VIPS_EXTEND_BACKGROUND, "background", vipsBackground, NULL); - - vips_area_unref(VIPS_AREA(vipsBackground)); - return code; -} - -int embed_multi_page_image(VipsImage *in, VipsImage **out, int left, int top, int width, - int height, int extend) { - VipsObject *base = VIPS_OBJECT(vips_image_new()); - int page_height = vips_image_get_page_height(in); - int in_width = in->Xsize; - int n_pages = in->Ysize / page_height; - - VipsImage **page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **embedded_page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **copy = (VipsImage **) vips_object_local_array(base, 1); - - // split image into cropped frames - for (int i = 0; i < n_pages; i++) { - if ( - vips_extract_area(in, &page[i], 0, page_height * i, in_width, page_height, NULL) || - vips_embed(page[i], &embedded_page[i], left, top, width, height, "extend", extend, NULL) - ) { - g_object_unref(base); - return -1; - } - } - // reassemble frames and set page height - // copy before modifying metadata - if( - vips_arrayjoin(embedded_page, ©[0], n_pages, "across", 1, NULL) || - vips_copy(copy[0], out, NULL) - ) { - g_object_unref(base); - return -1; - } - vips_image_set_int(*out, VIPS_META_PAGE_HEIGHT, height); - g_object_unref(base); - return 0; -} - -int embed_multi_page_image_background(VipsImage *in, VipsImage **out, int left, int top, int width, - int height, double r, double g, double b, double a) { - double background[4]; - int n = background_for_bands(in, background, r, g, b, a); - VipsArrayDouble *vipsBackground = vips_array_double_new(background, n); - - VipsObject *base = VIPS_OBJECT(vips_image_new()); - int page_height = vips_image_get_page_height(in); - int in_width = in->Xsize; - int n_pages = in->Ysize / page_height; - - VipsImage **page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **embedded_page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **copy = (VipsImage **) vips_object_local_array(base, 1); - - // split image into cropped frames - for (int i = 0; i < n_pages; i++) { - if ( - vips_extract_area(in, &page[i], 0, page_height * i, in_width, page_height, NULL) || - vips_embed(page[i], &embedded_page[i], left, top, width, height, - "extend", VIPS_EXTEND_BACKGROUND, "background", vipsBackground, NULL) - ) { - vips_area_unref(VIPS_AREA(vipsBackground)); - g_object_unref(base); - return -1; - } - } - // reassemble frames and set page height - // copy before modifying metadata - if( - vips_arrayjoin(embedded_page, ©[0], n_pages, "across", 1, NULL) || - vips_copy(copy[0], out, NULL) - ) { - vips_area_unref(VIPS_AREA(vipsBackground)); - g_object_unref(base); - return -1; - } - vips_image_set_int(*out, VIPS_META_PAGE_HEIGHT, height); - vips_area_unref(VIPS_AREA(vipsBackground)); - g_object_unref(base); - return 0; -} - - -int similarity(VipsImage *in, VipsImage **out, double scale, double angle, - double r, double g, double b, double a, double idx, double idy, - double odx, double ody) { - if (is_16bit(in->Type)) { - r = 65535 * r / 255; - g = 65535 * g / 255; - b = 65535 * b / 255; - a = 65535 * a / 255; - } - - double background[4]; - int n = background_for_bands(in, background, r, g, b, a); - VipsArrayDouble *vipsBackground = vips_array_double_new(background, n); - - int code = vips_similarity(in, out, "scale", scale, "angle", angle, - "background", vipsBackground, "idx", idx, "idy", - idy, "odx", odx, "ody", ody, NULL); - - vips_area_unref(VIPS_AREA(vipsBackground)); - return code; -} - -int crop(VipsImage *in, VipsImage **out, int left, int top, - int width, int height) { - // resolve image pages - int page_height = vips_image_get_page_height(in); - int n_pages = in->Ysize / page_height; - if (n_pages <= 1) { - return vips_crop(in, out, left, top, width, height, NULL); - } - - int in_width = in->Xsize; - VipsObject *base = VIPS_OBJECT(vips_image_new()); - VipsImage **page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **cropped_page = (VipsImage **) vips_object_local_array(base, n_pages); - VipsImage **copy = (VipsImage **) vips_object_local_array(base, 1); - // split image into cropped frames - for (int i = 0; i < n_pages; i++) { - if ( - vips_extract_area(in, &page[i], 0, page_height * i, in_width, page_height, NULL) || - vips_crop(page[i], &cropped_page[i], left, top, width, height, NULL) - ) { - g_object_unref(base); - return -1; - } - } - - // reassemble frames and set page height - // copy before modifying metadata - if( - vips_arrayjoin(cropped_page, ©[0], n_pages, "across", 1, NULL) || - vips_copy(copy[0], out, NULL) - ) { - g_object_unref(base); - return -1; - } - vips_image_set_int(*out, VIPS_META_PAGE_HEIGHT, height); - g_object_unref(base); - return 0; -} - -static int is_16bit(VipsInterpretation interpretation) { - return interpretation == VIPS_INTERPRETATION_RGB16 || - interpretation == VIPS_INTERPRETATION_GREY16; -} - -int composite_image(VipsImage **in, VipsImage **out, int n, int *mode, int *x, - int *y) { - VipsArrayInt *xs = vips_array_int_new(x, n - 1); - VipsArrayInt *ys = vips_array_int_new(y, n - 1); - - int code = vips_composite(in, out, n, mode, "x", xs, "y", ys, NULL); - - vips_area_unref(VIPS_AREA(xs)); - vips_area_unref(VIPS_AREA(ys)); - return code; -} - -int join(VipsImage *in1, VipsImage *in2, VipsImage **out, int direction) { - return vips_join(in1, in2, out, direction, NULL); -} - -int add_alpha(VipsImage *in, VipsImage **out) { - return vips_addalpha(in, out, NULL); -} - -// Create - -// https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text -int text(VipsImage **out, TextOptions *o) { - return vips_text(out, o->Text, "font", o->Font, "width", o->Width, "height", o->Height, "align", o->Align, - "dpi", o->DPI, "rgba", o->RGBA, "justify", o->Justify, "spacing", o->Spacing, "wrap", o->Wrap, NULL); -} - -// Draw - -int draw_rect(VipsImage *in, double r, double g, double b, double a, int left, - int top, int width, int height, int fill) { - if (is_16bit(in->Type)) { - r = 65535 * r / 255; - g = 65535 * g / 255; - b = 65535 * b / 255; - a = 65535 * a / 255; - } - - double ink[4]; - int n = background_for_bands(in, ink, r, g, b, a); - return vips_draw_rect(in, ink, n, left, top, width, height, "fill", fill, - NULL); -} - -// Header - -unsigned long has_icc_profile(VipsImage *in) { - return vips_image_get_typeof(in, VIPS_META_ICC_NAME); -} - -unsigned long get_icc_profile(VipsImage *in, const void **data, - size_t *dataLength) { - return image_get_blob(in, VIPS_META_ICC_NAME, data, dataLength); -} - -gboolean remove_icc_profile(VipsImage *in) { - return vips_image_remove(in, VIPS_META_ICC_NAME); -} - -unsigned long has_iptc(VipsImage *in) { - return vips_image_get_typeof(in, VIPS_META_IPTC_NAME); -} - -char **image_get_fields(VipsImage *in) { return vips_image_get_fields(in); } - -void image_set_string(VipsImage *in, const char *name, const char *str) { - vips_image_set_string(in, name, str); -} - -unsigned long image_get_string(VipsImage *in, const char *name, - const char **out) { - return vips_image_get_string(in, name, out); -} - -unsigned long image_get_as_string(VipsImage *in, const char *name, char **out) { - return vips_image_get_as_string(in, name, out); -} - -void remove_field(VipsImage *in, char *field) { vips_image_remove(in, field); } - -int get_meta_orientation(VipsImage *in) { - int orientation = 0; - if (vips_image_get_typeof(in, VIPS_META_ORIENTATION) != 0) { - vips_image_get_int(in, VIPS_META_ORIENTATION, &orientation); - } - - return orientation; -} - -void remove_meta_orientation(VipsImage *in) { - vips_image_remove(in, VIPS_META_ORIENTATION); -} - -void set_meta_orientation(VipsImage *in, int orientation) { - vips_image_set_int(in, VIPS_META_ORIENTATION, orientation); -} - -// https://libvips.github.io/libvips/API/current/libvips-header.html#vips-image-get-n-pages -int get_image_n_pages(VipsImage *in) { - int n_pages = 0; - n_pages = vips_image_get_n_pages(in); - return n_pages; -} - -void set_image_n_pages(VipsImage *in, int n_pages) { - vips_image_set_int(in, VIPS_META_N_PAGES, n_pages); -} - -// https://www.libvips.org/API/current/libvips-header.html#vips-image-get-page-height -int get_page_height(VipsImage *in) { - int page_height = 0; - page_height = vips_image_get_page_height(in); - return page_height; -} - -void set_page_height(VipsImage *in, int height) { - vips_image_set_int(in, VIPS_META_PAGE_HEIGHT, height); -} - -int get_meta_loader(const VipsImage *in, const char **out) { - return vips_image_get_string(in, VIPS_META_LOADER, out); -} - -int get_background(VipsImage *in, double **out, int *n) { - return vips_image_get_array_double(in, "background", out, n); -} - -int get_image_delay(VipsImage *in, int **out) { - return vips_image_get_array_int(in, "delay", out, NULL); -} - -void set_image_delay(VipsImage *in, const int *array, int n) { - vips_image_set_array_int(in, "delay", array, n); -} - -int get_image_loop(VipsImage *in) { - int loop = 0; - if (vips_image_get_typeof(in, "loop") != 0) { - vips_image_get_int(in, "loop", &loop); - } - return loop; -} - -void set_image_loop(VipsImage *in, int loop) { - vips_image_set_int(in, "loop", loop); -} - -void image_set_double(VipsImage *in, const char *name, double i) { - vips_image_set_double(in, name, i); -} - -unsigned long image_get_double(VipsImage *in, const char *name, double *out) { - return vips_image_get_double(in, name, out); -} - -void image_set_int(VipsImage *in, const char *name, int i) { - vips_image_set_int(in, name, i); -} - -unsigned long image_get_int(VipsImage *in, const char *name, int *out) { - return vips_image_get_int(in, name, out); -} - -void image_set_blob(VipsImage *in, const char *name, const void *data, - size_t dataLength) { - vips_image_set_blob_copy(in, name, data, dataLength); -} - -unsigned long image_get_blob(VipsImage *in, const char *name, const void **data, - size_t *dataLength) { - if (vips_image_get_typeof(in, name) == 0) { - return 0; - } - - if (vips_image_get_blob(in, name, data, dataLength)) { - return -1; - } - - return 0; -} - -// Label - -int label(VipsImage *in, VipsImage **out, LabelOptions *o) { - double ones[3] = {1, 1, 1}; - VipsImage *base = vips_image_new(); - VipsImage **t = (VipsImage **)vips_object_local_array(VIPS_OBJECT(base), 9); - if (vips_text(&t[0], o->Text, "font", o->Font, "width", o->Width, "height", - o->Height, "align", o->Align, NULL) || - vips_linear1(t[0], &t[1], o->Opacity, 0.0, NULL) || - vips_cast(t[1], &t[2], VIPS_FORMAT_UCHAR, NULL) || - vips_embed(t[2], &t[3], o->OffsetX, o->OffsetY, t[2]->Xsize + o->OffsetX, - t[2]->Ysize + o->OffsetY, NULL)) { - g_object_unref(base); - return -1; - } - if (vips_black(&t[4], 1, 1, NULL) || - vips_linear(t[4], &t[5], ones, o->Color, 3, NULL) || - vips_cast(t[5], &t[6], VIPS_FORMAT_UCHAR, NULL) || - vips_copy(t[6], &t[7], "interpretation", in->Type, NULL) || - vips_embed(t[7], &t[8], 0, 0, in->Xsize, in->Ysize, "extend", - VIPS_EXTEND_COPY, NULL)) { - g_object_unref(base); - return -1; - } - if (vips_ifthenelse(t[3], t[8], in, out, "blend", TRUE, NULL)) { - g_object_unref(base); - return -1; - } - g_object_unref(base); - return 0; -} - -// Resample - -int resize_image(VipsImage *in, VipsImage **out, double scale, gdouble vscale, - int kernel) { - if (vscale > 0) { - return vips_resize(in, out, scale, "vscale", vscale, "kernel", kernel, - NULL); - } - - return vips_resize(in, out, scale, "kernel", kernel, NULL); -} - -int thumbnail(const char *filename, VipsImage **out, - int width, int height, int crop, int size) { - return vips_thumbnail(filename, out, width, "height", height, - "crop", crop, "size", size, NULL); -} - -int thumbnail_image(VipsImage *in, VipsImage **out, int width, int height, - int crop, int size) { - return vips_thumbnail_image(in, out, width, "height", height, "crop", crop, - "size", size, NULL); -} - -int thumbnail_buffer_with_option(void *buf, size_t len, VipsImage **out, - int width, int height, int crop, int size, - const char *option_string) { - return vips_thumbnail_buffer(buf, len, out, width, "height", height, - "crop", crop, "size", size, - "option_string", option_string, NULL); -} - -int thumbnail_buffer(void *buf, size_t len, VipsImage **out, - int width, int height, int crop, int size) { - return vips_thumbnail_buffer(buf, len, out, width, "height", height, - "crop", crop, "size", size, NULL); -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/operations.go b/vendor/github.com/davidbyttow/govips/v2/vips/operations.go deleted file mode 100644 index faf2321b64..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/operations.go +++ /dev/null @@ -1,1083 +0,0 @@ -package vips - -// #cgo CFLAGS: -std=c99 -// #include "operations.h" -import "C" -import ( - "errors" - "os" - "runtime" - "strings" - "unsafe" -) - -// Arithmetic - -// https://libvips.github.io/libvips/API/current/libvips-arithmetic.html#vips-find-trim -func vipsFindTrim(in *C.VipsImage, threshold float64, backgroundColor *Color) (int, int, int, int, error) { - incOpCounter("findTrim") - var left, top, width, height C.int - - if err := C.find_trim(in, &left, &top, &width, &height, C.double(threshold), C.double(backgroundColor.R), - C.double(backgroundColor.G), C.double(backgroundColor.B)); err != 0 { - return -1, -1, -1, -1, handleVipsError() - } - - return int(left), int(top), int(width), int(height), nil -} - -// https://libvips.github.io/libvips/API/current/libvips-arithmetic.html#vips-getpoint -func vipsGetPoint(in *C.VipsImage, n int, x int, y int) ([]float64, error) { - incOpCounter("getpoint") - var out *C.double - - if err := C.getpoint(in, &out, C.int(n), C.int(x), C.int(y)); err != 0 { - return nil, handleVipsError() - } - - // Copy from C memory into a Go slice, then free the C allocation. - result := make([]float64, n) - copy(result, unsafe.Slice((*float64)(unsafe.Pointer(out)), n)) - gFreePointer(unsafe.Pointer(out)) - return result, nil -} - -// https://www.libvips.org/API/current/libvips-arithmetic.html#vips-min -func vipsMin(in *C.VipsImage) (float64, int, int, error) { - incOpCounter("min") - var out C.double - var x, y C.int - - if err := C.minOp(in, &out, &x, &y, C.int(1)); err != 0 { - return 0, 0, 0, handleVipsError() - } - - return float64(out), int(x), int(y), nil -} - -// Color - -// Color represents an RGB -type Color struct { - R, G, B uint8 -} - -// ColorRGBA represents an RGB with alpha channel (A) -type ColorRGBA struct { - R, G, B, A uint8 -} - -// Interpretation represents VIPS_INTERPRETATION type -type Interpretation int - -// Interpretation enum -const ( - InterpretationError Interpretation = C.VIPS_INTERPRETATION_ERROR - InterpretationMultiband Interpretation = C.VIPS_INTERPRETATION_MULTIBAND - InterpretationBW Interpretation = C.VIPS_INTERPRETATION_B_W - InterpretationHistogram Interpretation = C.VIPS_INTERPRETATION_HISTOGRAM - InterpretationXYZ Interpretation = C.VIPS_INTERPRETATION_XYZ - InterpretationLAB Interpretation = C.VIPS_INTERPRETATION_LAB - InterpretationCMYK Interpretation = C.VIPS_INTERPRETATION_CMYK - InterpretationLABQ Interpretation = C.VIPS_INTERPRETATION_LABQ - InterpretationRGB Interpretation = C.VIPS_INTERPRETATION_RGB - InterpretationRGB16 Interpretation = C.VIPS_INTERPRETATION_RGB16 - InterpretationCMC Interpretation = C.VIPS_INTERPRETATION_CMC - InterpretationLCH Interpretation = C.VIPS_INTERPRETATION_LCH - InterpretationLABS Interpretation = C.VIPS_INTERPRETATION_LABS - InterpretationSRGB Interpretation = C.VIPS_INTERPRETATION_sRGB - InterpretationYXY Interpretation = C.VIPS_INTERPRETATION_YXY - InterpretationFourier Interpretation = C.VIPS_INTERPRETATION_FOURIER - InterpretationGrey16 Interpretation = C.VIPS_INTERPRETATION_GREY16 - InterpretationMatrix Interpretation = C.VIPS_INTERPRETATION_MATRIX - InterpretationScRGB Interpretation = C.VIPS_INTERPRETATION_scRGB - InterpretationHSV Interpretation = C.VIPS_INTERPRETATION_HSV -) - -// Intent represents VIPS_INTENT type -type Intent int - -// Intent enum -const ( - IntentPerceptual Intent = C.VIPS_INTENT_PERCEPTUAL - IntentRelative Intent = C.VIPS_INTENT_RELATIVE - IntentSaturation Intent = C.VIPS_INTENT_SATURATION - IntentAbsolute Intent = C.VIPS_INTENT_ABSOLUTE - IntentLast Intent = C.VIPS_INTENT_LAST -) - -func vipsIsColorSpaceSupported(in *C.VipsImage) bool { - return C.is_colorspace_supported(in) == 1 -} - -// https://libvips.github.io/libvips/API/current/libvips-colour.html#vips-colourspace -func vipsToColorSpace(in *C.VipsImage, interpretation Interpretation) (*C.VipsImage, error) { - incOpCounter("to_colorspace") - var out *C.VipsImage - - inter := C.VipsInterpretation(interpretation) - - if err := C.to_colorspace(in, &out, inter); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -func vipsICCTransform(in *C.VipsImage, outputProfile string, inputProfile string, intent Intent, depth int, - embedded bool) (*C.VipsImage, error) { - var out *C.VipsImage - var cInputProfile *C.char - var cEmbedded C.gboolean - - cOutputProfile := C.CString(outputProfile) - defer freeCString(cOutputProfile) - - if inputProfile != "" { - cInputProfile = C.CString(inputProfile) - defer freeCString(cInputProfile) - } - - if embedded { - cEmbedded = C.TRUE - } - - if res := C.icc_transform(in, &out, cOutputProfile, cInputProfile, C.VipsIntent(intent), C.int(depth), cEmbedded); res != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// Composite - -// ImageComposite image to composite param -type ImageComposite struct { - Image *ImageRef - BlendMode BlendMode - X, Y int -} - -func toVipsCompositeStructs(r *ImageRef, datas []*ImageComposite) ([]*C.VipsImage, []C.int, []C.int, []C.int) { - ins := []*C.VipsImage{r.image} - modes := []C.int{} - xs := []C.int{} - ys := []C.int{} - - for _, image := range datas { - ins = append(ins, image.Image.image) - modes = append(modes, C.int(image.BlendMode)) - xs = append(xs, C.int(image.X)) - ys = append(ys, C.int(image.Y)) - } - - return ins, modes, xs, ys -} - -// Conversion - -// BandFormat represents VIPS_FORMAT type -type BandFormat int - -// BandFormat enum -const ( - BandFormatNotSet BandFormat = C.VIPS_FORMAT_NOTSET - BandFormatUchar BandFormat = C.VIPS_FORMAT_UCHAR - BandFormatChar BandFormat = C.VIPS_FORMAT_CHAR - BandFormatUshort BandFormat = C.VIPS_FORMAT_USHORT - BandFormatShort BandFormat = C.VIPS_FORMAT_SHORT - BandFormatUint BandFormat = C.VIPS_FORMAT_UINT - BandFormatInt BandFormat = C.VIPS_FORMAT_INT - BandFormatFloat BandFormat = C.VIPS_FORMAT_FLOAT - BandFormatComplex BandFormat = C.VIPS_FORMAT_COMPLEX - BandFormatDouble BandFormat = C.VIPS_FORMAT_DOUBLE - BandFormatDpComplex BandFormat = C.VIPS_FORMAT_DPCOMPLEX -) - -// BlendMode gives the various Porter-Duff and PDF blend modes. -// See https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode -type BlendMode int - -// Constants define the various Porter-Duff and PDF blend modes. -// See https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsBlendMode -const ( - BlendModeClear BlendMode = C.VIPS_BLEND_MODE_CLEAR - BlendModeSource BlendMode = C.VIPS_BLEND_MODE_SOURCE - BlendModeOver BlendMode = C.VIPS_BLEND_MODE_OVER - BlendModeIn BlendMode = C.VIPS_BLEND_MODE_IN - BlendModeOut BlendMode = C.VIPS_BLEND_MODE_OUT - BlendModeAtop BlendMode = C.VIPS_BLEND_MODE_ATOP - BlendModeDest BlendMode = C.VIPS_BLEND_MODE_DEST - BlendModeDestOver BlendMode = C.VIPS_BLEND_MODE_DEST_OVER - BlendModeDestIn BlendMode = C.VIPS_BLEND_MODE_DEST_IN - BlendModeDestOut BlendMode = C.VIPS_BLEND_MODE_DEST_OUT - BlendModeDestAtop BlendMode = C.VIPS_BLEND_MODE_DEST_ATOP - BlendModeXOR BlendMode = C.VIPS_BLEND_MODE_XOR - BlendModeAdd BlendMode = C.VIPS_BLEND_MODE_ADD - BlendModeSaturate BlendMode = C.VIPS_BLEND_MODE_SATURATE - BlendModeMultiply BlendMode = C.VIPS_BLEND_MODE_MULTIPLY - BlendModeScreen BlendMode = C.VIPS_BLEND_MODE_SCREEN - BlendModeOverlay BlendMode = C.VIPS_BLEND_MODE_OVERLAY - BlendModeDarken BlendMode = C.VIPS_BLEND_MODE_DARKEN - BlendModeLighten BlendMode = C.VIPS_BLEND_MODE_LIGHTEN - BlendModeColorDodge BlendMode = C.VIPS_BLEND_MODE_COLOUR_DODGE - BlendModeColorBurn BlendMode = C.VIPS_BLEND_MODE_COLOUR_BURN - BlendModeHardLight BlendMode = C.VIPS_BLEND_MODE_HARD_LIGHT - BlendModeSoftLight BlendMode = C.VIPS_BLEND_MODE_SOFT_LIGHT - BlendModeDifference BlendMode = C.VIPS_BLEND_MODE_DIFFERENCE - BlendModeExclusion BlendMode = C.VIPS_BLEND_MODE_EXCLUSION -) - -// Gravity represents VIPS_GRAVITY type -type Gravity int - -// Gravity enum -const ( - GravityCentre Gravity = C.VIPS_COMPASS_DIRECTION_CENTRE - GravityNorth Gravity = C.VIPS_COMPASS_DIRECTION_NORTH - GravityEast Gravity = C.VIPS_COMPASS_DIRECTION_EAST - GravitySouth Gravity = C.VIPS_COMPASS_DIRECTION_SOUTH - GravityWest Gravity = C.VIPS_COMPASS_DIRECTION_WEST - GravityNorthEast Gravity = C.VIPS_COMPASS_DIRECTION_NORTH_EAST - GravityNorthWest Gravity = C.VIPS_COMPASS_DIRECTION_NORTH_WEST - GravitySouthEast Gravity = C.VIPS_COMPASS_DIRECTION_SOUTH_EAST - GravitySouthWest Gravity = C.VIPS_COMPASS_DIRECTION_SOUTH_WEST -) - -// Direction represents VIPS_DIRECTION type -type Direction int - -// Direction enum -const ( - DirectionHorizontal Direction = C.VIPS_DIRECTION_HORIZONTAL - DirectionVertical Direction = C.VIPS_DIRECTION_VERTICAL -) - -// Angle represents VIPS_ANGLE type -type Angle int - -// Angle enum -const ( - Angle0 Angle = C.VIPS_ANGLE_D0 - Angle90 Angle = C.VIPS_ANGLE_D90 - Angle180 Angle = C.VIPS_ANGLE_D180 - Angle270 Angle = C.VIPS_ANGLE_D270 -) - -// Angle45 represents VIPS_ANGLE45 type -type Angle45 int - -// Angle45 enum -const ( - Angle45_0 Angle45 = C.VIPS_ANGLE45_D0 - Angle45_45 Angle45 = C.VIPS_ANGLE45_D45 - Angle45_90 Angle45 = C.VIPS_ANGLE45_D90 - Angle45_135 Angle45 = C.VIPS_ANGLE45_D135 - Angle45_180 Angle45 = C.VIPS_ANGLE45_D180 - Angle45_225 Angle45 = C.VIPS_ANGLE45_D225 - Angle45_270 Angle45 = C.VIPS_ANGLE45_D270 - Angle45_315 Angle45 = C.VIPS_ANGLE45_D315 -) - -// ExtendStrategy represents VIPS_EXTEND type -type ExtendStrategy int - -// ExtendStrategy enum -const ( - ExtendBlack ExtendStrategy = C.VIPS_EXTEND_BLACK - ExtendCopy ExtendStrategy = C.VIPS_EXTEND_COPY - ExtendRepeat ExtendStrategy = C.VIPS_EXTEND_REPEAT - ExtendMirror ExtendStrategy = C.VIPS_EXTEND_MIRROR - ExtendWhite ExtendStrategy = C.VIPS_EXTEND_WHITE - ExtendBackground ExtendStrategy = C.VIPS_EXTEND_BACKGROUND -) - -// Interesting represents VIPS_INTERESTING type -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#VipsInteresting -type Interesting int - -// Interesting constants represent areas of interest which smart cropping will crop based on. -const ( - InterestingNone Interesting = C.VIPS_INTERESTING_NONE - InterestingCentre Interesting = C.VIPS_INTERESTING_CENTRE - InterestingEntropy Interesting = C.VIPS_INTERESTING_ENTROPY - InterestingAttention Interesting = C.VIPS_INTERESTING_ATTENTION - InterestingLow Interesting = C.VIPS_INTERESTING_LOW - InterestingHigh Interesting = C.VIPS_INTERESTING_HIGH - InterestingAll Interesting = C.VIPS_INTERESTING_ALL - InterestingLast Interesting = C.VIPS_INTERESTING_LAST -) - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-embed -func vipsEmbed(in *C.VipsImage, left, top, width, height int, extend ExtendStrategy) (*C.VipsImage, error) { - incOpCounter("embed") - var out *C.VipsImage - - if err := C.embed_image(in, &out, C.int(left), C.int(top), C.int(width), C.int(height), C.int(extend)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-embed -func vipsEmbedBackground(in *C.VipsImage, left, top, width, height int, backgroundColor *ColorRGBA) (*C.VipsImage, error) { - incOpCounter("embed") - var out *C.VipsImage - - if err := C.embed_image_background(in, &out, C.int(left), C.int(top), C.int(width), - C.int(height), C.double(backgroundColor.R), - C.double(backgroundColor.G), C.double(backgroundColor.B), C.double(backgroundColor.A)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -func vipsEmbedMultiPage(in *C.VipsImage, left, top, width, height int, extend ExtendStrategy) (*C.VipsImage, error) { - incOpCounter("embedMultiPage") - var out *C.VipsImage - - if err := C.embed_multi_page_image(in, &out, C.int(left), C.int(top), C.int(width), C.int(height), C.int(extend)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -func vipsEmbedMultiPageBackground(in *C.VipsImage, left, top, width, height int, backgroundColor *ColorRGBA) (*C.VipsImage, error) { - incOpCounter("embedMultiPageBackground") - var out *C.VipsImage - - if err := C.embed_multi_page_image_background(in, &out, C.int(left), C.int(top), C.int(width), - C.int(height), C.double(backgroundColor.R), - C.double(backgroundColor.G), C.double(backgroundColor.B), C.double(backgroundColor.A)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-flip -func vipsFlip(in *C.VipsImage, direction Direction) (*C.VipsImage, error) { - return vipsGenFlip(in, direction) -} - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-extract-area -func vipsExtractArea(in *C.VipsImage, left, top, width, height int) (*C.VipsImage, error) { - return vipsGenExtractArea(in, left, top, width, height) -} - -func vipsExtractAreaMultiPage(in *C.VipsImage, left, top, width, height int) (*C.VipsImage, error) { - incOpCounter("extractAreaMultiPage") - - return vipsMapPages(in, func(page *C.VipsImage) (*C.VipsImage, error) { - return vipsGenExtractArea(page, left, top, width, height) - }) -} - -// vipsMapPages applies op to each loaded page of a multi-page image and -// restacks the results. Operations that act on the whole strip (flip, -// rot180, resize) would otherwise reorder or merge the frames. The page -// height of the result is taken from the first mapped page. -func vipsMapPages(in *C.VipsImage, op func(page *C.VipsImage) (*C.VipsImage, error)) (*C.VipsImage, error) { - pageHeight := vipsGetPageHeight(in) - nPages := int(in.Ysize) / pageHeight - if nPages < 1 { - nPages, pageHeight = 1, int(in.Ysize) - } - - pages := make([]*C.VipsImage, 0, nPages) - defer func() { - for _, p := range pages { - clearImage(p) - } - }() - for i := 0; i < nPages; i++ { - page, err := vipsGenExtractArea(in, 0, pageHeight*i, int(in.Xsize), pageHeight) - if err != nil { - return nil, err - } - mapped, err := op(page) - clearImage(page) - if err != nil { - return nil, err - } - pages = append(pages, mapped) - } - - across := 1 - joined, err := vipsGenArrayjoin(pages, &ArrayjoinOptions{Across: &across}) - if err != nil { - return nil, err - } - - out, err := vipsGenCopy(joined, nil) - clearImage(joined) - if err != nil { - return nil, err - } - - vipsSetPageHeight(out, int(pages[0].Ysize)) - return out, nil -} - -// http://libvips.github.io/libvips/API/current/libvips-resample.html#vips-similarity -func vipsSimilarity(in *C.VipsImage, scale float64, angle float64, color *ColorRGBA, - idx float64, idy float64, odx float64, ody float64) (*C.VipsImage, error) { - incOpCounter("similarity") - var out *C.VipsImage - - if err := C.similarity(in, &out, C.double(scale), C.double(angle), - C.double(color.R), C.double(color.G), C.double(color.B), C.double(color.A), - C.double(idx), C.double(idy), C.double(odx), C.double(ody)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// http://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-smartcrop -func vipsSmartCrop(in *C.VipsImage, width int, height int, interesting Interesting) (*C.VipsImage, error) { - _, out, _, err := vipsGenSmartcrop(in, width, height, &SmartcropOptions{Interesting: &interesting}) - return out, err -} - -// http://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-crop -func vipsCrop(in *C.VipsImage, left int, top int, width int, height int) (*C.VipsImage, error) { - incOpCounter("crop") - var out *C.VipsImage - - if err := C.crop(in, &out, C.int(left), C.int(top), C.int(width), C.int(height)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-composite -func vipsComposite(ins []*C.VipsImage, modes []C.int, xs, ys []C.int) (*C.VipsImage, error) { - if len(ins) == 0 || len(modes) == 0 || len(xs) == 0 || len(ys) == 0 { - return nil, errors.New("vipsComposite: empty input slice") - } - incOpCounter("composite_multi") - var out *C.VipsImage - - if err := C.composite_image(&ins[0], &out, C.int(len(ins)), &modes[0], &xs[0], &ys[0]); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// https://libvips.github.io/libvips/API/current/libvips-conversion.html#vips-join -func vipsJoin(input1 *C.VipsImage, input2 *C.VipsImage, dir Direction) (*C.VipsImage, error) { - incOpCounter("join") - var out *C.VipsImage - - // NOTE: do NOT unref input1/input2 here. They are borrowed from the - // caller's ImageRefs, which own those references and unref them in - // Close/finalize. vips_join takes its own refs on its inputs for the - // lifetime of the output. Unref'ing here drops refs we never owned, - // which double-frees the inputs once their ImageRefs are collected. - if err := C.join(input1, input2, &out, C.int(dir)); err != 0 { - return nil, handleVipsError() - } - return out, nil -} - -func vipsAddAlpha(in *C.VipsImage) (*C.VipsImage, error) { - incOpCounter("addalpha") - var out *C.VipsImage - - if err := C.add_alpha(in, &out); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// Create - -type TextWrap int - -type TextParams struct { - Text string - Font string - Width int - Height int - Alignment Align - DPI int - RGBA bool - Justify bool - Spacing int - Wrap TextWrap -} - -type vipsTextOptions struct { - Text *C.char - Font *C.char - Width C.int - Height C.int - DPI C.int - RGBA C.gboolean - Justify C.gboolean - Spacing C.int - Alignment C.VipsAlign - Wrap C.VipsTextWrap -} - -// TextWrap enum -const ( - TextWrapWord TextWrap = C.VIPS_TEXT_WRAP_WORD - TextWrapChar TextWrap = C.VIPS_TEXT_WRAP_CHAR - TextWrapWordChar TextWrap = C.VIPS_TEXT_WRAP_WORD_CHAR - TextWrapNone TextWrap = C.VIPS_TEXT_WRAP_NONE -) - -// https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text -func vipsText(params *TextParams) (*C.VipsImage, error) { - var out *C.VipsImage - - text := C.CString(params.Text) - defer freeCString(text) - - font := C.CString(params.Font) - defer freeCString(font) - - opts := vipsTextOptions{ - Text: text, - Font: font, - Width: C.int(params.Width), - Height: C.int(params.Height), - DPI: C.int(params.DPI), - Alignment: C.VipsAlign(params.Alignment), - Spacing: C.int(params.Spacing), - Wrap: C.VipsTextWrap(params.Wrap), - } - - if params.RGBA { - opts.RGBA = C.TRUE - } - - if params.Justify { - opts.Justify = C.TRUE - } - - err := C.text(&out, (*C.TextOptions)(unsafe.Pointer(&opts))) - if err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// Draw - -// https://libvips.github.io/libvips/API/current/libvips-draw.html#vips-draw-rect -func vipsDrawRect(in *C.VipsImage, color ColorRGBA, left int, top int, width int, height int, fill bool) error { - incOpCounter("draw_rect") - - fillBit := 0 - if fill { - fillBit = 1 - } - - if err := C.draw_rect(in, C.double(color.R), C.double(color.G), C.double(color.B), C.double(color.A), - C.int(left), C.int(top), C.int(width), C.int(height), C.int(fillBit)); err != 0 { - // draw_rect works in place: there's no output image to release, and - // the ref on in belongs to the caller's ImageRef. - return handleVipsError() - } - - return nil -} - -// Header - -func vipsHasICCProfile(in *C.VipsImage) bool { - return int(C.has_icc_profile(in)) != 0 -} - -func vipsGetICCProfile(in *C.VipsImage) ([]byte, bool) { - var bufPtr unsafe.Pointer - var dataLength C.size_t - - if int(C.get_icc_profile(in, &bufPtr, &dataLength)) != 0 { - return nil, false - } - - buf := C.GoBytes(bufPtr, C.int(dataLength)) - return buf, true -} - -func vipsRemoveICCProfile(in *C.VipsImage) bool { - return fromGboolean(C.remove_icc_profile(in)) -} - -func vipsHasIPTC(in *C.VipsImage) bool { - return int(C.has_iptc(in)) != 0 -} - -func vipsImageGetFields(in *C.VipsImage) (fields []string) { - const maxFields = 256 - - rawFields := C.image_get_fields(in) - defer C.g_strfreev(rawFields) - - cFields := (*[maxFields]*C.char)(unsafe.Pointer(rawFields))[:maxFields:maxFields] - - for _, field := range cFields { - if field == nil { - break - } - fields = append(fields, C.GoString(field)) - } - return -} - -func vipsImageGetExifData(in *C.VipsImage) map[string]string { - fields := vipsImageGetFields(in) - - exifData := map[string]string{} - for _, field := range fields { - if strings.HasPrefix(field, "exif") { - exifData[field] = vipsImageGetString(in, field) - } - } - - return exifData -} - -func vipsRemoveMetadata(in *C.VipsImage, keep ...string) { - fields := vipsImageGetFields(in) - - retain := append(keep, technicalMetadata...) - - for _, field := range fields { - if contains(retain, field) { - continue - } - - cField := C.CString(field) - - C.remove_field(in, cField) - - C.free(unsafe.Pointer(cField)) - } -} - -var technicalMetadata = []string{ - C.VIPS_META_ICC_NAME, - C.VIPS_META_ORIENTATION, - C.VIPS_META_N_PAGES, - C.VIPS_META_PAGE_HEIGHT, - "delay", - "loop", -} - -func contains(a []string, x string) bool { - for _, n := range a { - if x == n { - return true - } - } - return false -} - -func vipsGetMetaOrientation(in *C.VipsImage) int { - return int(C.get_meta_orientation(in)) -} - -func vipsRemoveMetaOrientation(in *C.VipsImage) { - C.remove_meta_orientation(in) -} - -func vipsSetMetaOrientation(in *C.VipsImage, orientation int) { - C.set_meta_orientation(in, C.int(orientation)) -} - -func vipsGetImageNPages(in *C.VipsImage) int { - return int(C.get_image_n_pages(in)) -} - -func vipsSetImageNPages(in *C.VipsImage, pages int) { - C.set_image_n_pages(in, C.int(pages)) -} - -func vipsGetPageHeight(in *C.VipsImage) int { - return int(C.get_page_height(in)) -} - -func vipsSetPageHeight(in *C.VipsImage, height int) { - C.set_page_height(in, C.int(height)) -} - -func vipsImageGetMetaLoader(in *C.VipsImage) (string, bool) { - var out *C.char - code := int(C.get_meta_loader(in, &out)) - return C.GoString(out), code == 0 -} - -func vipsImageGetDelay(in *C.VipsImage, n int) ([]int, error) { - incOpCounter("imageGetDelay") - var out *C.int - - if err := C.get_image_delay(in, &out); err != 0 { - return nil, handleVipsError() - } - return fromCArrayInt(out, n), nil -} - -func vipsImageSetDelay(in *C.VipsImage, data []C.int) error { - incOpCounter("imageSetDelay") - if n := len(data); n > 0 { - C.set_image_delay(in, &data[0], C.int(n)) - } - return nil -} - -func vipsImageGetLoop(in *C.VipsImage) int { - return int(C.get_image_loop(in)) -} - -func vipsImageSetLoop(in *C.VipsImage, loop int) { - C.set_image_loop(in, C.int(loop)) -} - -func vipsImageGetBackground(in *C.VipsImage) ([]float64, error) { - incOpCounter("imageGetBackground") - var out *C.double - var n C.int - - if err := C.get_background(in, &out, &n); err != 0 { - return nil, handleVipsError() - } - return fromCArrayDouble(out, int(n)), nil -} - -// vipsDetermineImageTypeFromMetaLoader determine the image type from vips-loader metadata -func vipsDetermineImageTypeFromMetaLoader(in *C.VipsImage) ImageType { - vipsLoader, ok := vipsImageGetMetaLoader(in) - if vipsLoader == "" || !ok { - return ImageTypeUnknown - } - if strings.HasPrefix(vipsLoader, "jpeg") { - return ImageTypeJPEG - } - if strings.HasPrefix(vipsLoader, "png") { - return ImageTypePNG - } - if strings.HasPrefix(vipsLoader, "gif") { - return ImageTypeGIF - } - if strings.HasPrefix(vipsLoader, "svg") { - return ImageTypeSVG - } - if strings.HasPrefix(vipsLoader, "webp") { - return ImageTypeWEBP - } - if strings.HasPrefix(vipsLoader, "jp2k") { - return ImageTypeJP2K - } - if strings.HasPrefix(vipsLoader, "jxl") { - return ImageTypeJXL - } - if strings.HasPrefix(vipsLoader, "magick") { - return ImageTypeMagick - } - if strings.HasPrefix(vipsLoader, "tiff") { - return ImageTypeTIFF - } - if strings.HasPrefix(vipsLoader, "heif") { - return ImageTypeHEIF - } - if strings.HasPrefix(vipsLoader, "pdf") { - return ImageTypePDF - } - return ImageTypeUnknown -} - -func vipsImageSetBlob(in *C.VipsImage, name string, data []byte) { - if len(data) == 0 { - return - } - - cField := C.CString(name) - defer freeCString(cField) - C.image_set_blob(in, cField, unsafe.Pointer(&data[0]), C.size_t(len(data))) -} - -func vipsImageGetBlob(in *C.VipsImage, name string) []byte { - var bufPtr unsafe.Pointer - var dataLength C.size_t - - cField := C.CString(name) - defer freeCString(cField) - if int(C.image_get_blob(in, cField, &bufPtr, &dataLength)) != 0 { - return nil - } - - buf := C.GoBytes(bufPtr, C.int(dataLength)) - return buf -} - -func vipsImageSetDouble(in *C.VipsImage, name string, f float64) { - cField := C.CString(name) - defer freeCString(cField) - - cDouble := C.double(f) - C.image_set_double(in, cField, cDouble) -} - -func vipsImageGetDouble(in *C.VipsImage, name string) float64 { - cField := C.CString(name) - defer freeCString(cField) - - var cDouble C.double - if int(C.image_get_double(in, cField, &cDouble)) == 0 { - return float64(cDouble) - } - - return 0 -} - -func vipsImageSetInt(in *C.VipsImage, name string, i int) { - cField := C.CString(name) - defer freeCString(cField) - - cInt := C.int(i) - C.image_set_int(in, cField, cInt) -} - -func vipsImageGetInt(in *C.VipsImage, name string) int { - cField := C.CString(name) - defer freeCString(cField) - - var cInt C.int - if int(C.image_get_int(in, cField, &cInt)) == 0 { - return int(cInt) - } - - return 0 -} - -func vipsImageSetString(in *C.VipsImage, name string, str string) { - cField := C.CString(name) - defer freeCString(cField) - - cStr := C.CString(str) - defer freeCString(cStr) - - C.image_set_string(in, cField, cStr) -} - -func vipsImageGetString(in *C.VipsImage, name string) string { - cField := C.CString(name) - defer freeCString(cField) - var cFieldValue *C.char - if int(C.image_get_string(in, cField, &cFieldValue)) == 0 { - return C.GoString(cFieldValue) - } - - return "" -} - -func vipsImageGetAsString(in *C.VipsImage, name string) string { - cField := C.CString(name) - defer freeCString(cField) - var cFieldValue *C.char - defer func() { freeCString(cFieldValue) }() - if int(C.image_get_as_string(in, cField, &cFieldValue)) == 0 { - return C.GoString(cFieldValue) - } - - return "" -} - -// Label - -// Align represents VIPS_ALIGN -type Align int - -// Direction enum -const ( - AlignLow Align = C.VIPS_ALIGN_LOW - AlignCenter Align = C.VIPS_ALIGN_CENTRE - AlignHigh Align = C.VIPS_ALIGN_HIGH -) - -// DefaultFont is the default font to be used for label texts created by govips -const DefaultFont = "sans 10" - -// LabelParams represents a text-based label -type LabelParams struct { - Text string - Font string - Width Scalar - Height Scalar - OffsetX Scalar - OffsetY Scalar - Opacity float32 - Color Color - Alignment Align -} - -type vipsLabelOptions struct { - Text *C.char - Font *C.char - Width C.int - Height C.int - OffsetX C.int - OffsetY C.int - Alignment C.VipsAlign - DPI C.int - Margin C.int - Opacity C.float - Color [3]C.double -} - -func labelImage(in *C.VipsImage, params *LabelParams) (*C.VipsImage, error) { - incOpCounter("label") - var out *C.VipsImage - - text := C.CString(params.Text) - defer freeCString(text) - - font := C.CString(params.Font) - defer freeCString(font) - - // todo: release color? - color := [3]C.double{C.double(params.Color.R), C.double(params.Color.G), C.double(params.Color.B)} - - w := params.Width.GetRounded(int(in.Xsize)) - h := params.Height.GetRounded(int(in.Ysize)) - offsetX := params.OffsetX.GetRounded(int(in.Xsize)) - offsetY := params.OffsetY.GetRounded(int(in.Ysize)) - - opts := vipsLabelOptions{ - Text: text, - Font: font, - Width: C.int(w), - Height: C.int(h), - OffsetX: C.int(offsetX), - OffsetY: C.int(offsetY), - Alignment: C.VipsAlign(params.Alignment), - Opacity: C.float(params.Opacity), - Color: color, - } - - // todo: release inline pointer? - err := C.label(in, &out, (*C.LabelOptions)(unsafe.Pointer(&opts))) - if err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// Resample - -// Kernel represents VipsKernel type -type Kernel int - -// Kernel enum -const ( - KernelAuto Kernel = -1 - KernelNearest Kernel = C.VIPS_KERNEL_NEAREST - KernelLinear Kernel = C.VIPS_KERNEL_LINEAR - KernelCubic Kernel = C.VIPS_KERNEL_CUBIC - KernelLanczos2 Kernel = C.VIPS_KERNEL_LANCZOS2 - KernelLanczos3 Kernel = C.VIPS_KERNEL_LANCZOS3 - KernelMitchell Kernel = C.VIPS_KERNEL_MITCHELL -) - -// Size represents VipsSize type -type Size int - -const ( - SizeBoth Size = C.VIPS_SIZE_BOTH - SizeUp Size = C.VIPS_SIZE_UP - SizeDown Size = C.VIPS_SIZE_DOWN - SizeForce Size = C.VIPS_SIZE_FORCE - SizeLast Size = C.VIPS_SIZE_LAST -) - -// https://libvips.github.io/libvips/API/current/libvips-resample.html#vips-resize -func vipsResizeWithVScale(in *C.VipsImage, hscale, vscale float64, kernel Kernel) (*C.VipsImage, error) { - incOpCounter("resize") - var out *C.VipsImage - - // libvips recommends Lanczos3 as the default kernel - if kernel == KernelAuto { - kernel = KernelLanczos3 - } - - if err := C.resize_image(in, &out, C.double(hscale), C.double(vscale), C.int(kernel)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -func vipsThumbnail(in *C.VipsImage, width, height int, crop Interesting, size Size) (*C.VipsImage, error) { - incOpCounter("thumbnail") - var out *C.VipsImage - - if err := C.thumbnail_image(in, &out, C.int(width), C.int(height), C.int(crop), C.int(size)); err != 0 { - return nil, handleImageError(out) - } - - return out, nil -} - -// https://www.libvips.org/API/current/libvips-resample.html#vips-thumbnail -func vipsThumbnailFromFile(filename string, width, height int, crop Interesting, size Size, params *ImportParams) (*C.VipsImage, ImageType, error) { - var out *C.VipsImage - - filenameOption := filename - if params != nil { - filenameOption += "[" + params.OptionString() + "]" - } - - cFileName := C.CString(filenameOption) - defer freeCString(cFileName) - - if err := C.thumbnail(cFileName, &out, C.int(width), C.int(height), C.int(crop), C.int(size)); err != 0 { - err := handleImageError(out) - if src, err2 := os.ReadFile(filename); err2 == nil { - return vipsThumbnailFromBuffer(src, width, height, crop, size, params) - } - return nil, ImageTypeUnknown, err - } - - imageType := vipsDetermineImageTypeFromMetaLoader(out) - return out, imageType, nil -} - -// https://www.libvips.org/API/current/libvips-resample.html#vips-thumbnail-buffer -func vipsThumbnailFromBuffer(buf []byte, width, height int, crop Interesting, size Size, params *ImportParams) (*C.VipsImage, ImageType, error) { - src := buf - // Reference src here so it's not garbage collected during image initialization. - defer runtime.KeepAlive(src) - - var out *C.VipsImage - - var err C.int - - if params == nil { - err = C.thumbnail_buffer(unsafe.Pointer(&src[0]), C.size_t(len(src)), &out, C.int(width), C.int(height), C.int(crop), C.int(size)) - } else { - cOptionString := C.CString(params.OptionString()) - defer freeCString(cOptionString) - - err = C.thumbnail_buffer_with_option(unsafe.Pointer(&src[0]), C.size_t(len(src)), &out, C.int(width), C.int(height), C.int(crop), C.int(size), cOptionString) - } - if err != 0 { - err := handleImageError(out) - return nil, ImageTypeUnknown, err - } - - imageType := vipsDetermineImageTypeFromMetaLoader(out) - return out, imageType, nil -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/operations.h b/vendor/github.com/davidbyttow/govips/v2/vips/operations.h deleted file mode 100644 index e2fe167d9b..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/operations.h +++ /dev/null @@ -1,149 +0,0 @@ -// operations.h - Hand-written C bridge functions for libvips operations - -#ifndef OPERATIONS_H -#define OPERATIONS_H - -#include -#include -#include - -// Arithmetic -// https://libvips.github.io/libvips/API/current/libvips-arithmetic.html - -int find_trim(VipsImage *in, int *left, int *top, int *width, int *height, - double threshold, double r, double g, double b); -int getpoint(VipsImage *in, double **vector, int n, int x, int y); -int minOp(VipsImage *in, double *out, int *x, int *y, int size); - -// Color -// https://libvips.github.io/libvips/API/current/libvips-colour.html - -int is_colorspace_supported(VipsImage *in); -int to_colorspace(VipsImage *in, VipsImage **out, VipsInterpretation space); -int icc_transform(VipsImage *in, VipsImage **out, const char *output_profile, - const char *input_profile, VipsIntent intent, int depth, - gboolean embedded); - -// Conversion -// https://libvips.github.io/libvips/API/current/libvips-conversion.html - -int embed_image(VipsImage *in, VipsImage **out, int left, int top, int width, - int height, int extend); -int embed_image_background(VipsImage *in, VipsImage **out, int left, int top, - int width, int height, double r, double g, double b, double a); -int embed_multi_page_image(VipsImage *in, VipsImage **out, int left, int top, - int width, int height, int extend); -int embed_multi_page_image_background(VipsImage *in, VipsImage **out, int left, - int top, int width, int height, double r, double g, double b, - double a); -int crop(VipsImage *in, VipsImage **out, int left, int top, int width, - int height); -int similarity(VipsImage *in, VipsImage **out, double scale, double angle, - double r, double g, double b, double a, double idx, double idy, - double odx, double ody); -int composite_image(VipsImage **in, VipsImage **out, int n, int *mode, int *x, - int *y); -int join(VipsImage *in1, VipsImage *in2, VipsImage **out, int direction); -int add_alpha(VipsImage *in, VipsImage **out); - -// Create -// https://libvips.github.io/libvips/API/current/libvips-create.html - -typedef struct { - const char *Text; - const char *Font; - int Width; - int Height; - int DPI; - gboolean RGBA; - gboolean Justify; - int Spacing; - VipsAlign Align; - VipsTextWrap Wrap; -} TextOptions; - -int text(VipsImage **out, TextOptions *o); - -// Draw -// https://libvips.github.io/libvips/API/current/libvips-draw.html - -int draw_rect(VipsImage *in, double r, double g, double b, double a, int left, - int top, int width, int height, int fill); - -// Header -// https://libvips.github.io/libvips/API/current/libvips-header.html - -unsigned long has_icc_profile(VipsImage *in); -unsigned long get_icc_profile(VipsImage *in, const void **data, - size_t *dataLength); -int remove_icc_profile(VipsImage *in); - -unsigned long has_iptc(VipsImage *in); -char **image_get_fields(VipsImage *in); - -void image_set_string(VipsImage *in, const char *name, const char *str); -unsigned long image_get_string(VipsImage *in, const char *name, - const char **out); -unsigned long image_get_as_string(VipsImage *in, const char *name, char **out); - -void remove_field(VipsImage *in, char *field); - -int get_meta_orientation(VipsImage *in); -void remove_meta_orientation(VipsImage *in); -void set_meta_orientation(VipsImage *in, int orientation); -int get_image_n_pages(VipsImage *in); -void set_image_n_pages(VipsImage *in, int n_pages); -int get_page_height(VipsImage *in); -void set_page_height(VipsImage *in, int height); -int get_meta_loader(const VipsImage *in, const char **out); -int get_image_delay(VipsImage *in, int **out); -void set_image_delay(VipsImage *in, const int *array, int n); -int get_image_loop(VipsImage *in); -void set_image_loop(VipsImage *in, int loop); -int get_background(VipsImage *in, double **out, int *n); - -void image_set_blob(VipsImage *in, const char *name, const void *data, - size_t dataLength); -unsigned long image_get_blob(VipsImage *in, const char *name, const void **data, - size_t *dataLength); - -void image_set_double(VipsImage *in, const char *name, double i); -unsigned long image_get_double(VipsImage *in, const char *name, double *out); - -void image_set_int(VipsImage *in, const char *name, int i); -unsigned long image_get_int(VipsImage *in, const char *name, int *out); - -// Label - -typedef struct { - const char *Text; - const char *Font; - int Width; - int Height; - int OffsetX; - int OffsetY; - VipsAlign Align; - int DPI; - int Margin; - float Opacity; - double Color[3]; -} LabelOptions; - -int label(VipsImage *in, VipsImage **out, LabelOptions *o); - -// Resample -// https://libvips.github.io/libvips/API/current/libvips-resample.html - -int resize_image(VipsImage *in, VipsImage **out, double scale, gdouble vscale, - int kernel); -int thumbnail(const char *filename, VipsImage **out, int width, int height, - int crop, int size); -int thumbnail_image(VipsImage *in, VipsImage **out, int width, int height, - int crop, int size); -int thumbnail_buffer(void *buf, size_t len, VipsImage **out, int width, - int height, int crop, int size); -int thumbnail_buffer_with_option(void *buf, size_t len, VipsImage **out, - int width, int height, int crop, int size, - const char *option_string); - -#endif // OPERATIONS_H diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/stats.go b/vendor/github.com/davidbyttow/govips/v2/vips/stats.go deleted file mode 100644 index d3208c75cf..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/stats.go +++ /dev/null @@ -1,56 +0,0 @@ -package vips - -import "sync" - -// RuntimeStats is a data structure to house a map of govips operation counts -type RuntimeStats struct { - OperationCounts map[string]int64 -} - -var ( - operationCounter chan string - runtimeStats *RuntimeStats - statLock sync.RWMutex -) - -func incOpCounter(op string) { - if operationCounter != nil { - operationCounter <- op - } -} - -func collectStats() chan struct{} { - operationCounter = make(chan string, 100) - done := make(chan struct{}) - exit := false - go func() { - for !exit { - select { - case op := <-operationCounter: - statLock.Lock() - runtimeStats.OperationCounts[op] = runtimeStats.OperationCounts[op] + 1 - statLock.Unlock() - case <-done: - exit = true - break - } - } - }() - return done -} - -// ReadRuntimeStats returns operation counts for govips -func ReadRuntimeStats(stats *RuntimeStats) { - statLock.RLock() - defer statLock.RUnlock() - stats.OperationCounts = make(map[string]int64) - for k, v := range runtimeStats.OperationCounts { - stats.OperationCounts[k] = v - } -} - -func init() { - runtimeStats = &RuntimeStats{ - OperationCounts: make(map[string]int64), - } -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/stream.c b/vendor/github.com/davidbyttow/govips/v2/vips/stream.c deleted file mode 100644 index 66fc9b5950..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/stream.c +++ /dev/null @@ -1,316 +0,0 @@ -#include "stream.h" - -#include - -// Option setters shared with the buffer path, defined in foreign.c. -// Reusing them keeps streaming output identical to the buffer output. -extern int set_jpegload_options(VipsOperation *operation, LoadParams *params); -extern int set_pngload_options(VipsOperation *operation, LoadParams *params); -extern int set_webpload_options(VipsOperation *operation, LoadParams *params); -extern int set_tiffload_options(VipsOperation *operation, LoadParams *params); -extern int set_gifload_options(VipsOperation *operation, LoadParams *params); -extern int set_heifload_options(VipsOperation *operation, LoadParams *params); -extern int set_svgload_options(VipsOperation *operation, LoadParams *params); -extern int set_pdfload_options(VipsOperation *operation, LoadParams *params); -extern int set_jp2kload_options(VipsOperation *operation, LoadParams *params); -extern int set_jxlload_options(VipsOperation *operation, LoadParams *params); -extern int set_magickload_options(VipsOperation *operation, LoadParams *params); - -extern int set_jpegsave_options(VipsOperation *operation, SaveParams *params); -extern int set_pngsave_options(VipsOperation *operation, SaveParams *params); -extern int set_webpsave_options(VipsOperation *operation, SaveParams *params); -extern int set_heifsave_options(VipsOperation *operation, SaveParams *params); -extern int set_tiffsave_options(VipsOperation *operation, SaveParams *params); -extern int set_gifsave_options(VipsOperation *operation, SaveParams *params); - -// Trampolines: extract the registry handle from signal user_data and -// forward to the exported Go callbacks. Buffers are owned by libvips and -// only valid for the duration of the call. - -static gint64 source_read_handler(VipsSourceCustom *source, void *buffer, - gint64 length, void *user_data) { - (void)source; - return goSourceReadCb(GPOINTER_TO_INT(user_data), buffer, length); -} - -static gint64 source_seek_handler(VipsSourceCustom *source, gint64 offset, - int whence, void *user_data) { - (void)source; - return goSourceSeekCb(GPOINTER_TO_INT(user_data), offset, whence); -} - -static gint64 target_write_handler(VipsTargetCustom *target, const void *data, - gint64 length, void *user_data) { - (void)target; - return goTargetWriteCb(GPOINTER_TO_INT(user_data), (void *)data, length); -} - -static int target_end_handler(VipsTargetCustom *target, void *user_data) { - (void)target; - return goTargetEndCb(GPOINTER_TO_INT(user_data)); -} - -VipsSourceCustom *create_source_custom(int handle, int has_seek) { - VipsSourceCustom *source = vips_source_custom_new(); - if (!source) { - return NULL; - } - - g_signal_connect(source, "read", G_CALLBACK(source_read_handler), - GINT_TO_POINTER(handle)); - if (has_seek) { - g_signal_connect(source, "seek", G_CALLBACK(source_seek_handler), - GINT_TO_POINTER(handle)); - } - - return source; -} - -VipsTargetCustom *create_target_custom(int handle) { - VipsTargetCustom *target = vips_target_custom_new(); - if (!target) { - return NULL; - } - - g_signal_connect(target, "write", G_CALLBACK(target_write_handler), - GINT_TO_POINTER(handle)); - g_signal_connect(target, "end", G_CALLBACK(target_end_handler), - GINT_TO_POINTER(handle)); - - return target; -} - -int source_sniff_header(VipsSourceCustom *source, unsigned char *out, int len) { - const unsigned char *p = vips_source_sniff(VIPS_SOURCE(source), (size_t) len); - if (!p) { - return -1; - } - memcpy(out, p, (size_t) len); - return 0; -} - -static ImageType image_type_for_loader(const char *name) { - if (g_str_has_prefix(name, "jpegload")) return JPEG; - if (g_str_has_prefix(name, "pngload")) return PNG; - if (g_str_has_prefix(name, "webpload")) return WEBP; - if (g_str_has_prefix(name, "tiffload")) return TIFF; - if (g_str_has_prefix(name, "gifload")) return GIF; - if (g_str_has_prefix(name, "heifload")) return HEIF; - if (g_str_has_prefix(name, "svgload")) return SVG; - if (g_str_has_prefix(name, "pdfload")) return PDF; - if (g_str_has_prefix(name, "jp2kload")) return JP2K; - if (g_str_has_prefix(name, "jxlload")) return JXL; - if (g_str_has_prefix(name, "magickload")) return MAGICK; - return UNKNOWN; -} - -typedef int (*SetLoadOptionsFn)(VipsOperation *operation, LoadParams *params); - -static int set_noload_options(VipsOperation *operation, LoadParams *params) { - (void)operation; - (void)params; - return 0; -} - -static SetLoadOptionsFn load_options_for_type(ImageType imageType) { - switch (imageType) { - case JPEG: - return set_jpegload_options; - case PNG: - return set_pngload_options; - case WEBP: - return set_webpload_options; - case TIFF: - return set_tiffload_options; - case GIF: - return set_gifload_options; - case HEIF: - return set_heifload_options; - case SVG: - return set_svgload_options; - case PDF: - return set_pdfload_options; - case JP2K: - return set_jp2kload_options; - case JXL: - return set_jxlload_options; - case MAGICK: - return set_magickload_options; - default: - return set_noload_options; - } -} - -int load_from_source(VipsSourceCustom *source, LoadParams *params) { - // Sniffs the stream start to find a loader. This returns the GType - // class name (e.g. "VipsForeignLoadJpegSource"); resolve it to the - // operation nickname (e.g. "jpegload_source") for format mapping. - const char *className = vips_foreign_find_load_source(VIPS_SOURCE(source)); - if (!className) { - return 1; - } - const char *operationName = vips_nickname_find(g_type_from_name(className)); - if (!operationName) { - return 1; - } - - params->inputFormat = image_type_for_loader(operationName); - SetLoadOptionsFn setLoadOptions = load_options_for_type(params->inputFormat); - - VipsOperation *operation = vips_operation_new(operationName); - if (!operation) { - return 1; - } - - if (vips_object_set(VIPS_OBJECT(operation), "source", source, NULL)) { - g_object_unref(operation); - return 1; - } - - if (setLoadOptions(operation, params)) { - g_object_unref(operation); - return 1; - } - - // The deprecated "fail" bool does not make every loader reject - // truncated input (e.g. spng pads missing rows with only a warning). - // Streaming inputs are network-shaped, so when the caller asked for - // fail-on-error escalate to the modern fail_on property at the - // "truncated" level: truncated streams fail, ordinary warnings on - // valid images do not. - if (params->fail.is_set && params->fail.value.b && - g_object_class_find_property(G_OBJECT_GET_CLASS(operation), - "fail_on")) { - vips_object_set(VIPS_OBJECT(operation), "fail_on", - VIPS_FAIL_ON_TRUNCATED, NULL); - } - - // Build uncached: the cache key includes the unique source object, so - // a hit is impossible — caching would only pin the source and the - // lazy image in the operation cache past their natural lifetime. - if (vips_object_build(VIPS_OBJECT(operation))) { - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - return 1; - } - - g_object_get(VIPS_OBJECT(operation), "out", ¶ms->outputImage, NULL); - - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - - // The returned image is LAZY: libvips decodes on demand, pulling from - // the source during later operations. The Go side decides whether to - // materialize it now (memory or scratch disc, releasing the source - // early) or keep the source connected for sequential streaming. - return 0; -} - -gint64 image_decoded_size(VipsImage *in) { - return (gint64)VIPS_IMAGE_SIZEOF_PEL(in) * in->Xsize * in->Ysize; -} - -int copy_image_to_memory(VipsImage *in, VipsImage **out) { - VipsImage *memory = vips_image_copy_memory(in); - if (!memory) { - return 1; - } - *out = memory; - return 0; -} - -int write_image_to_disc(VipsImage *in, const char *path, VipsImage **out) { - // Render the full image to a vips-native (.v) scratch file in one - // sequential pass, then reopen it as a random-access image backed by - // the file. Decode/reader errors surface here, during the write pass. - if (vips_image_write_to_file(in, path, NULL)) { - return 1; - } - - VipsImage *disc = - vips_image_new_from_file(path, "access", VIPS_ACCESS_RANDOM, NULL); - if (!disc) { - return 1; - } - *out = disc; - return 0; -} - -typedef int (*SetSaveOptionsFn)(VipsOperation *operation, SaveParams *params); - -static int save_target(const char *operationName, SaveParams *params, - VipsTargetCustom *target, - SetSaveOptionsFn setSaveOptions) { - VipsOperation *operation = vips_operation_new(operationName); - if (!operation) { - return 1; - } - - if (vips_object_set(VIPS_OBJECT(operation), "in", params->inputImage, - "target", target, NULL)) { - g_object_unref(operation); - return 1; - } - - if (setSaveOptions(operation, params)) { - g_object_unref(operation); - return 1; - } - - // Same as save_buffer: "keep" overrides the deprecated "strip". - if (params->keepSet && - vips_object_set(VIPS_OBJECT(operation), "keep", params->keep, NULL)) { - g_object_unref(operation); - return 1; - } - - // Build uncached, mirroring load_from_source: the unique target - // object makes cache hits impossible. - if (vips_object_build(VIPS_OBJECT(operation))) { - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - return 1; - } - - vips_object_unref_outputs(VIPS_OBJECT(operation)); - g_object_unref(operation); - - return 0; -} - -int save_jpeg_to_target(SaveParams *params, VipsTargetCustom *target) { - return save_target("jpegsave_target", params, target, set_jpegsave_options); -} - -int save_png_to_target(SaveParams *params, VipsTargetCustom *target) { - return save_target("pngsave_target", params, target, set_pngsave_options); -} - -int save_webp_to_target(SaveParams *params, VipsTargetCustom *target) { - return save_target("webpsave_target", params, target, set_webpsave_options); -} - -int save_heif_to_target(SaveParams *params, VipsTargetCustom *target) { - return save_target("heifsave_target", params, target, set_heifsave_options); -} - -// No save_tiff_to_target: libtiff requires seekable output, so the Go -// side always encodes TIFF through the buffer path. - -int save_gif_to_target(SaveParams *params, VipsTargetCustom *target) { - return save_target("gifsave_target", params, target, set_gifsave_options); -} - -void clear_source(VipsSourceCustom **source) { - if (source && *source) { - g_object_unref(*source); - *source = NULL; - } -} - -void clear_target(VipsTargetCustom **target) { - if (target && *target) { - g_object_unref(*target); - *target = NULL; - } -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/stream.go b/vendor/github.com/davidbyttow/govips/v2/vips/stream.go deleted file mode 100644 index f23d9a1889..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/stream.go +++ /dev/null @@ -1,842 +0,0 @@ -package vips - -// Streaming I/O via VipsSourceCustom/VipsTargetCustom. -// -// libvips worker threads pull/push bytes through C trampolines (stream.c) -// that dispatch to the exported Go callbacks below via integer handles in -// a global registry. Holding a registry reference also keeps the Go -// reader/writer alive while the C side may still call back into it. - -// #include "stream.h" -import "C" - -import ( - "errors" - "fmt" - "io" - "math" - "os" - "runtime" - "strconv" - "strings" - "sync" - "unsafe" -) - -// sourceEntry is the registry entry for one streaming load. The mutex -// serializes callback invocations so callers never need thread-safe -// readers, even though libvips may call from multiple worker threads. -type sourceEntry struct { - reader io.Reader - seeker io.Seeker // non-nil only when reader implements io.Seeker - mu sync.Mutex - lastErr error - - // size is the lazily resolved length of the seekable source, - // cached for clamping past-EOF seek targets. Guarded by mu. - size int64 - sizeKnown bool -} - -// sourceSizeLocked resolves and caches the source length without -// disturbing the current position. The entry mutex must be held. -func (e *sourceEntry) sourceSizeLocked() (int64, error) { - if e.sizeKnown { - return e.size, nil - } - cur, err := e.seeker.Seek(0, io.SeekCurrent) - if err != nil { - return 0, err - } - size, err := e.seeker.Seek(0, io.SeekEnd) - if err != nil { - return 0, err - } - if _, err := e.seeker.Seek(cur, io.SeekStart); err != nil { - return 0, err - } - e.size, e.sizeKnown = size, true - return size, nil -} - -// targetEntry is the registry entry for one streaming save. -type targetEntry struct { - writer io.Writer - mu sync.Mutex - lastErr error -} - -func (e *sourceEntry) takeErr() error { - e.mu.Lock() - defer e.mu.Unlock() - err := e.lastErr - e.lastErr = nil - return err -} - -func (e *targetEntry) takeErr() error { - e.mu.Lock() - defer e.mu.Unlock() - err := e.lastErr - e.lastErr = nil - return err -} - -// streamCallbacks maps integer handles to active source/target entries. -// The registry mutex only guards the maps; per-entry mutexes guard the -// actual I/O so the global lock is never held during a Read/Write. -var streamCallbacks = struct { - sync.Mutex - sources map[int]*sourceEntry - targets map[int]*targetEntry - nextHandle int -}{ - sources: make(map[int]*sourceEntry), - targets: make(map[int]*targetEntry), -} - -// allocStreamHandle returns the next free handle. Handles cross the CGo -// boundary as C int (via GLib's GINT_TO_POINTER), so they must stay -// within int32 range: wrap instead of overflowing, and skip any handle -// that is still registered after a wrap. The caller must hold the -// streamCallbacks lock. -func allocStreamHandle() int { - for { - streamCallbacks.nextHandle++ - if streamCallbacks.nextHandle > math.MaxInt32 { - streamCallbacks.nextHandle = 1 - } - h := streamCallbacks.nextHandle - if _, live := streamCallbacks.sources[h]; live { - continue - } - if _, live := streamCallbacks.targets[h]; live { - continue - } - return h - } -} - -func registerSource(r io.Reader) (int, *sourceEntry) { - entry := &sourceEntry{reader: r} - if s, ok := r.(io.Seeker); ok { - entry.seeker = s - } - - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - handle := allocStreamHandle() - streamCallbacks.sources[handle] = entry - return handle, entry -} - -func deregisterSource(handle int) { - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - delete(streamCallbacks.sources, handle) -} - -func lookupSource(handle int) *sourceEntry { - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - return streamCallbacks.sources[handle] -} - -func registerTarget(w io.Writer) (int, *targetEntry) { - entry := &targetEntry{writer: w} - - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - handle := allocStreamHandle() - streamCallbacks.targets[handle] = entry - return handle, entry -} - -func deregisterTarget(handle int) { - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - delete(streamCallbacks.targets, handle) -} - -func lookupTarget(handle int) *targetEntry { - streamCallbacks.Lock() - defer streamCallbacks.Unlock() - return streamCallbacks.targets[handle] -} - -//export goSourceReadCb -func goSourceReadCb(handle C.int, buffer unsafe.Pointer, length C.gint64) C.gint64 { - if length <= 0 { - return 0 - } - buf := unsafe.Slice((*byte)(buffer), int(length)) - return C.gint64(sourceRead(int(handle), buf)) -} - -//export goSourceSeekCb -func goSourceSeekCb(handle C.int, offset C.gint64, whence C.int) C.gint64 { - return C.gint64(sourceSeek(int(handle), int64(offset), int(whence))) -} - -//export goTargetWriteCb -func goTargetWriteCb(handle C.int, data unsafe.Pointer, length C.gint64) C.gint64 { - if length <= 0 { - return 0 - } - buf := unsafe.Slice((*byte)(data), int(length)) - return C.gint64(targetWrite(int(handle), buf)) -} - -//export goTargetEndCb -func goTargetEndCb(handle C.int) C.int { - return C.int(targetEnd(int(handle))) -} - -func sourceRead(handle int, buf []byte) int64 { - entry := lookupSource(handle) - if entry == nil { - return -1 - } - - entry.mu.Lock() - defer entry.mu.Unlock() - - // (0, nil) is allowed by the io.Reader contract; retry rather than - // returning 0, which libvips would treat as EOF. Bound the retries so - // a pathological reader that returns (0, nil) forever fails the load - // instead of pinning a libvips worker thread inside this callback. - const maxZeroReads = 100 - for i := 0; i < maxZeroReads; i++ { - n, err := entry.reader.Read(buf) - if n > 0 { - // A non-EOF error alongside n>0 will surface on the next call. - return int64(n) - } - if errors.Is(err, io.EOF) { - return 0 - } - if err != nil { - entry.lastErr = err - return -1 - } - } - entry.lastErr = fmt.Errorf("reader returned (0, nil) %d times in a row", maxZeroReads) - return -1 -} - -func sourceSeek(handle int, offset int64, whence int) int64 { - entry := lookupSource(handle) - if entry == nil || entry.seeker == nil { - return -1 - } - - entry.mu.Lock() - defer entry.mu.Unlock() - - size, err := entry.sourceSizeLocked() - if err != nil { - entry.lastErr = err - return -1 - } - - // Resolve the absolute target ourselves. libvips whence values are - // SEEK_SET/SEEK_CUR/SEEK_END, matching io.SeekStart/Current/End. - var base int64 - switch whence { - case io.SeekStart: - base = 0 - case io.SeekCurrent: - cur, err := entry.seeker.Seek(0, io.SeekCurrent) - if err != nil { - entry.lastErr = err - return -1 - } - base = cur - case io.SeekEnd: - base = size - default: - return -1 - } - - target := base + offset - if target < 0 { - // POSIX lseek rejects negative positions (EINVAL) without - // affecting the stream; treat it as a probe, not a stream - // error, so it is not wrapped into the load error later. - return -1 - } - if target > size { - // POSIX permits seeking beyond EOF, and codecs probe container - // structures that way (libheif seeks past the final HEIC box). - // Report the requested position: libvips itself range-checks it - // against the source length and turns it into the failure the - // heif glue's wait_for_file_size protocol relies on. Park the - // underlying seeker at EOF so strict io.Seeker implementations - // are never asked for an out-of-range position; any read then - // returns 0 bytes. One divergence from POSIX: a subsequent - // SEEK_CUR resolves from EOF, not from the reported past-EOF - // position. That is fine in practice because libvips' codec glue - // only ever follows a past-EOF probe with an absolute seek. - if _, err := entry.seeker.Seek(size, io.SeekStart); err != nil { - entry.lastErr = err - return -1 - } - return target - } - - pos, err := entry.seeker.Seek(target, io.SeekStart) - if err != nil { - entry.lastErr = err - return -1 - } - return pos -} - -func targetWrite(handle int, buf []byte) int64 { - entry := lookupTarget(handle) - if entry == nil { - return -1 - } - - entry.mu.Lock() - defer entry.mu.Unlock() - - n, err := entry.writer.Write(buf) - if err != nil { - entry.lastErr = err - return -1 - } - return int64(n) -} - -func targetEnd(handle int) int { - entry := lookupTarget(handle) - if entry == nil { - return -1 - } - - entry.mu.Lock() - defer entry.mu.Unlock() - - if entry.lastErr != nil { - return -1 - } - return 0 -} - -// streamSourceRef ties a live VipsSourceCustom (and its registry entry) -// to a sequentially stream-loaded ImageRef. The image pulls pixels from -// the source on demand, so both stay alive until the image is closed or -// materialized. -type streamSourceRef struct { - handle int - entry *sourceEntry - source *C.VipsSourceCustom -} - -func (s *streamSourceRef) release() { - C.clear_source(&s.source) - deregisterSource(s.handle) -} - -// streamMaterialize holds the knobs for the default (random-access) -// load path: decoded images at most threshold bytes are materialized in -// memory, larger ones in a scratch file on disc. -var streamMaterialize = struct { - sync.RWMutex - scratchDir string // "" → os.TempDir() - threshold int64 // <0 → resolve from VIPS_DISC_THRESHOLD / default -}{threshold: -1} - -// defaultDiscThreshold mirrors the libvips default for -// VIPS_DISC_THRESHOLD: decoded images above 100 MB go to disc. -const defaultDiscThreshold = 100 << 20 - -// SetStreamScratchDir sets the directory used for scratch files when a -// stream-loaded image is materialized to disc (see -// SetStreamDiscThreshold). An empty string restores the default -// (os.TempDir()). Scratch files are unlinked as soon as the decoded -// image has been written and reopened, so on the happy path they never -// outlive the ImageRef; a crash mid-materialization can leave one -// behind in this directory. -func SetStreamScratchDir(dir string) { - streamMaterialize.Lock() - defer streamMaterialize.Unlock() - streamMaterialize.scratchDir = dir -} - -// SetStreamDiscThreshold sets the decoded-size threshold (in bytes) -// above which LoadImageFromReader materializes images to a scratch file -// on disc instead of memory. Zero sends every image to disc. A negative -// value restores the default: the VIPS_DISC_THRESHOLD environment -// variable (number with optional k/m/g suffix) or 100 MB. -func SetStreamDiscThreshold(bytes int64) { - streamMaterialize.Lock() - defer streamMaterialize.Unlock() - streamMaterialize.threshold = bytes -} - -func streamDiscThresholdBytes() int64 { - streamMaterialize.RLock() - t := streamMaterialize.threshold - streamMaterialize.RUnlock() - if t >= 0 { - return t - } - if env := os.Getenv("VIPS_DISC_THRESHOLD"); env != "" { - if v, ok := parseVipsSize(env); ok { - return v - } - } - return defaultDiscThreshold -} - -func streamScratchDir() string { - streamMaterialize.RLock() - defer streamMaterialize.RUnlock() - if streamMaterialize.scratchDir != "" { - return streamMaterialize.scratchDir - } - return os.TempDir() -} - -// parseVipsSize parses libvips-style size strings: a number with an -// optional k/m/g suffix (powers of 1024). -func parseVipsSize(s string) (int64, bool) { - s = strings.TrimSpace(strings.ToLower(s)) - mult := int64(1) - switch { - case strings.HasSuffix(s, "k"): - mult, s = 1<<10, s[:len(s)-1] - case strings.HasSuffix(s, "m"): - mult, s = 1<<20, s[:len(s)-1] - case strings.HasSuffix(s, "g"): - mult, s = 1<<30, s[:len(s)-1] - } - v, err := strconv.ParseFloat(strings.TrimSpace(s), 64) - if err != nil || v < 0 { - return 0, false - } - return int64(v * float64(mult)), true -} - -// materializeImage renders the lazy image in to either memory or a -// scratch file on disc, depending on its decoded size and the configured -// threshold. The returned image no longer reads from the source. -func materializeImage(in *C.VipsImage) (*C.VipsImage, error) { - decoded := int64(C.image_decoded_size(in)) - - if decoded <= streamDiscThresholdBytes() { - var out *C.VipsImage - if C.copy_image_to_memory(in, &out) != 0 { - return nil, handleVipsError() - } - return out, nil - } - - f, err := os.CreateTemp(streamScratchDir(), "govips-scratch-*.v") - if err != nil { - return nil, fmt.Errorf("streaming load: create scratch file: %w", err) - } - path := f.Name() - _ = f.Close() - - cPath := C.CString(path) - defer C.free(unsafe.Pointer(cPath)) - - var out *C.VipsImage - code := C.write_image_to_disc(in, cPath, &out) - // Unlink immediately: the open file keeps the data alive until the - // image is closed. (A crash during write_image_to_disc itself can - // still leave the scratch file behind; see SetStreamScratchDir.) - _ = os.Remove(path) - if code != 0 { - return nil, handleVipsError() - } - return out, nil -} - -// sequentialAccess reports whether params request sequential streaming. -func sequentialAccess(params *ImportParams) bool { - if !params.Access.IsSet() { - return false - } - a := params.Access.Get() - return a == AccessSequential || a == AccessSequentialUnbuffered -} - -// LoadImageFromReader loads an image from the given io.Reader using -// libvips streaming (VipsSourceCustom). If r also implements io.Seeker, -// seek is exposed to libvips for efficient random-access loading. -// Otherwise libvips uses sequential mode with automatic header buffering -// (see SetPipeReadLimit). -// -// By default the image is fully materialized before this function -// returns — in memory when its decoded size is at most the disc -// threshold, otherwise in an unlinked scratch file (see -// SetStreamDiscThreshold and SetStreamScratchDir). The reader is -// consumed during this call and is not retained; callers may close it -// immediately. Decode errors (including truncated input) surface here. -// -// If params.Access is AccessSequential, the image is instead loaded -// lazily: libvips pulls compressed bytes from r on demand while later -// operations consume pixels, so peak memory stays bounded by libvips -// line caches regardless of image size. The reader MUST stay open until -// the ImageRef is closed (Close releases it). Only operations that read -// pixels strictly top-to-bottom are valid on such images — see the -// "Streaming" section of the README. Decode errors surface from the -// operation that first consumes the pixels (typically SaveToWriter or -// Export*), not from this function. -// -// In every mode the returned ImageRef has no buffer backing: the full -// compressed input is never held in Go memory. (NewImageFromReader, by -// contrast, slurps the whole reader into a buffer via io.ReadAll before -// decoding; prefer this function when input size matters.) -// -// Error strictness: when params.FailOnError is set, streaming loads use -// libvips' fail_on=truncated, which is slightly laxer than the -// fail_on=error used by the buffer loaders — truncated input always -// errors deterministically, but some recoverable decode warnings that -// the buffer path would reject are tolerated. -// -// params may be nil for default import settings. -func LoadImageFromReader(r io.Reader, params *ImportParams) (*ImageRef, error) { - if r == nil { - return nil, errors.New("reader is nil") - } - if err := startupIfNeeded(); err != nil { - return nil, err - } - if params == nil { - params = NewImportParams() - } - - incOpCounter("load_source") - - handle, entry := registerSource(r) - - source := C.create_source_custom(C.int(handle), C.int(boolToInt(entry.seeker != nil))) - if source == nil { - deregisterSource(handle) - return nil, handleVipsError() - } - - // Sniff the signature up front (buffered and rewound, not consumed): - // the loader nickname alone cannot express sub-formats — AVIF loads - // via heifload, BMP/PSD via magickload — but the buffer path reports - // them via DetermineImageType, and the streaming path must match. - var header [12]byte - headerKnown := C.source_sniff_header(source, (*C.uchar)(unsafe.Pointer(&header[0])), C.int(len(header))) == 0 - - loadParams := createImportParams(ImageTypeUnknown, params) - - if code := C.load_from_source(source, &loadParams); code != 0 { - err := wrapStreamError("streaming load", handleImageError(loadParams.outputImage), entry.takeErr()) - C.clear_source(&source) - deregisterSource(handle) - return nil, err - } - - lazy := loadParams.outputImage - format := ImageType(loadParams.inputFormat) - originalFormat := format - if headerKnown && (format == ImageTypeHEIF || format == ImageTypeMagick) { - if sniffed := DetermineImageType(header[:]); sniffed != ImageTypeUnknown { - originalFormat = sniffed - if !isNeedToChangeLoaderToMagick(sniffed) { - format = sniffed - } - } - } - - if sequentialAccess(params) { - ref := newImageRef(lazy, format, originalFormat, nil) - ref.streamSource = &streamSourceRef{handle: handle, entry: entry, source: source} - govipsLog("govips", LogLevelDebug, fmt.Sprintf("created sequential imageRef %p from reader", ref)) - return ref, nil - } - - // Default path: materialize now so the source (and the caller's - // reader) can be released before returning. Upstream resources - // (file handles, HTTP connections) are freed early. - out, err := materializeImage(lazy) - clearImage(lazy) - C.clear_source(&source) - deregisterSource(handle) - if err != nil { - return nil, wrapStreamError("streaming load", err, entry.takeErr()) - } - - ref := newImageRef(out, format, originalFormat, nil) - govipsLog("govips", LogLevelDebug, fmt.Sprintf("created imageRef %p from reader", ref)) - return ref, nil -} - -// materialize converts a sequentially stream-loaded image into a -// materialized one (memory or scratch disc, by threshold) and releases -// its source, making random-access operations valid. It is a no-op for -// images that are already materialized. -func (r *ImageRef) materialize() error { - r.lock.Lock() - - if r.image == nil { - r.lock.Unlock() - return errors.New("attempt to materialize a closed ImageRef") - } - src := r.streamSource - if src == nil { - r.lock.Unlock() - return nil - } - - out, err := materializeImage(r.image) - if err != nil { - r.lock.Unlock() - return wrapStreamError("streaming load", err, src.entry.takeErr()) - } - - clearImage(r.image) - r.image = out - r.streamSource = nil - r.lock.Unlock() - - src.release() - return nil -} - -// SaveToWriter encodes the image in the specified format and writes the -// encoded bytes directly to w using libvips streaming (VipsTargetCustom). -// The writer receives chunks of encoded data as they are produced and is -// not retained after SaveToWriter returns. -// -// Supported formats: ImageTypeJPEG, ImageTypePNG, ImageTypeWEBP, -// ImageTypeHEIF, ImageTypeTIFF, ImageTypeGIF. Output is byte-identical to -// the corresponding Export* method with equivalent parameters. -// -// TIFF is encoded in memory and written in a single chunk, because the -// TIFF container requires seekable output; all other formats stream -// encoded chunks to w as they are produced. -// -// params may be nil for the format's default export settings; the format -// argument takes precedence over params.Format. For access to the full -// set of format-specific options, use the typed variants -// (SaveToWriterJpeg, SaveToWriterPng, SaveToWriterWebp, SaveToWriterTiff, -// SaveToWriterHeif, SaveToWriterGif). -func (r *ImageRef) SaveToWriter(w io.Writer, format ImageType, params *ExportParams) error { - return r.saveToWriter(w, format, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - return streamSaveParams(in, format, params) - }) -} - -// SaveToWriterJpeg streams the image to w as JPEG with the full set of -// JPEG export options. Behaves like SaveToWriter; params may be nil for -// defaults. Output is byte-identical to ExportJpeg. -func (r *ImageRef) SaveToWriterJpeg(w io.Writer, params *JpegExportParams) error { - if params == nil { - params = NewJpegExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypeJPEG, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - sp, err := newSaveParamsJPEG(in, p) - return sp, func() {}, err - }) -} - -// SaveToWriterPng streams the image to w as PNG with the full set of PNG -// export options (Palette, Dither, Bitdepth, Filter, ...). Behaves like -// SaveToWriter; params may be nil for defaults. Output is byte-identical -// to ExportPng. -func (r *ImageRef) SaveToWriterPng(w io.Writer, params *PngExportParams) error { - if params == nil { - params = NewPngExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypePNG, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - sp, err := newSaveParamsPNG(in, p) - return sp, func() {}, err - }) -} - -// SaveToWriterWebp streams the image to w as WebP with the full set of -// WebP export options (NearLossless, IccProfile, TargetSize, ...). -// Behaves like SaveToWriter; params may be nil for defaults. Output is -// byte-identical to ExportWebp. -func (r *ImageRef) SaveToWriterWebp(w io.Writer, params *WebpExportParams) error { - if params == nil { - params = NewWebpExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypeWEBP, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - return newSaveParamsWebP(in, p) - }) -} - -// SaveToWriterTiff writes the image to w as TIFF with the full set of -// TIFF export options (Compression, Predictor, Tile, ...). Like the TIFF -// path of SaveToWriter, the image is encoded in memory and written in a -// single chunk (libtiff requires seekable output). params may be nil for -// defaults. Output is byte-identical to ExportTiff. -func (r *ImageRef) SaveToWriterTiff(w io.Writer, params *TiffExportParams) error { - if params == nil { - params = NewTiffExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypeTIFF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - sp, err := newSaveParamsTIFF(in, p) - return sp, func() {}, err - }) -} - -// SaveToWriterHeif streams the image to w as HEIF with the full set of -// HEIF export options (Bitdepth, Effort, ...). Behaves like SaveToWriter; -// params may be nil for defaults. Output is byte-identical to ExportHeif. -func (r *ImageRef) SaveToWriterHeif(w io.Writer, params *HeifExportParams) error { - if params == nil { - params = NewHeifExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypeHEIF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - sp, err := newSaveParamsHEIF(in, p) - return sp, func() {}, err - }) -} - -// SaveToWriterGif streams the image to w as GIF with the full set of GIF -// export options (Dither, Effort, Bitdepth, ...). Behaves like -// SaveToWriter; params may be nil for defaults. Output is byte-identical -// to ExportGIF. -func (r *ImageRef) SaveToWriterGif(w io.Writer, params *GifExportParams) error { - if params == nil { - params = NewGifExportParams() - } - p := *params - return r.saveToWriter(w, ImageTypeGIF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) { - sp, err := newSaveParamsGIF(in, p) - return sp, func() {}, err - }) -} - -// saveToWriter is the shared core of SaveToWriter and its typed -// variants: it locks the image, builds the C save params via -// buildParams, and runs the streaming (or, for TIFF, buffered) save. -func (r *ImageRef) saveToWriter(w io.Writer, format ImageType, buildParams func(*C.VipsImage) (C.struct_SaveParams, func(), error)) error { - if w == nil { - return errors.New("writer is nil") - } - - r.lock.Lock() - defer r.lock.Unlock() - defer runtime.KeepAlive(r) - - if r.image == nil { - return errors.New("attempt to save a closed ImageRef") - } - - saveParams, cleanup, err := buildParams(r.image) - if err != nil { - return err - } - defer cleanup() - - incOpCounter("save_" + ImageTypes[format] + "_target") - - if format == ImageTypeTIFF { - // libtiff requires a seekable, readable output stream (it - // rewrites IFD offsets after encoding), which a plain io.Writer - // cannot provide. Encode through the buffer path and emit a - // single write; the bytes are identical to ExportTiff. - buf, err := vipsSaveToBuffer(saveParams) - if err != nil { - var ioErr error - if r.streamSource != nil { - // Sequential decode runs during this encode; surface - // the reader's error like the streaming-target path. - ioErr = r.streamSource.entry.takeErr() - } - return wrapStreamError("streaming save", err, ioErr) - } - if _, err := w.Write(buf); err != nil { - return fmt.Errorf("streaming save: writer error: %w", err) - } - return nil - } - - handle, entry := registerTarget(w) - defer deregisterTarget(handle) - - target := C.create_target_custom(C.int(handle)) - if target == nil { - return handleVipsError() - } - defer C.clear_target(&target) - - var code C.int - switch format { - case ImageTypeJPEG: - code = C.save_jpeg_to_target(&saveParams, target) - case ImageTypePNG: - code = C.save_png_to_target(&saveParams, target) - case ImageTypeWEBP: - code = C.save_webp_to_target(&saveParams, target) - case ImageTypeHEIF: - code = C.save_heif_to_target(&saveParams, target) - // ImageTypeTIFF is handled by the buffer-path early return above. - case ImageTypeGIF: - code = C.save_gif_to_target(&saveParams, target) - } - - if code != 0 { - ioErr := entry.takeErr() - if ioErr == nil && r.streamSource != nil { - // For sequentially stream-loaded images the decode runs - // during this save; surface the reader's error too. - ioErr = r.streamSource.entry.takeErr() - } - return wrapStreamError("streaming save", handleVipsError(), ioErr) - } - if ioErr := entry.takeErr(); ioErr != nil { - return fmt.Errorf("streaming save: writer error: %w", ioErr) - } - return nil -} - -// streamSaveParams builds the C save parameters for SaveToWriter using -// the same ExportParams mapping as (*ImageRef).Export (via the shared -// *ParamsFromExport helpers) and the same C-struct population as the -// Export* buffer savers, so streaming output stays byte-identical to the -// buffer path. The returned cleanup must be called after the save -// completes. -func streamSaveParams(in *C.VipsImage, format ImageType, params *ExportParams) (C.struct_SaveParams, func(), error) { - noop := func() {} - - switch format { - case ImageTypeJPEG: - p, err := newSaveParamsJPEG(in, *jpegParamsFromExport(params)) - return p, noop, err - case ImageTypePNG: - p, err := newSaveParamsPNG(in, *pngParamsFromExport(params)) - return p, noop, err - case ImageTypeWEBP: - return newSaveParamsWebP(in, *webpParamsFromExport(params)) - case ImageTypeHEIF: - p, err := newSaveParamsHEIF(in, *heifParamsFromExport(params)) - return p, noop, err - case ImageTypeTIFF: - p, err := newSaveParamsTIFF(in, *tiffParamsFromExport(params)) - return p, noop, err - case ImageTypeGIF: - p, err := newSaveParamsGIF(in, *gifParamsFromExport(params)) - return p, noop, err - default: - return C.struct_SaveParams{}, noop, fmt.Errorf("streaming save does not support format %q", ImageTypes[format]) - } -} - -// wrapStreamError combines the libvips error with the original Go -// reader/writer error, when one was stored during a callback. -func wrapStreamError(op string, vipsErr, ioErr error) error { - if ioErr != nil { - return fmt.Errorf("%s: %w (caused by: %w)", op, vipsErr, ioErr) - } - return vipsErr -} diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/stream.h b/vendor/github.com/davidbyttow/govips/v2/vips/stream.h deleted file mode 100644 index 459f1302cf..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/stream.h +++ /dev/null @@ -1,85 +0,0 @@ -// Streaming I/O via VipsSourceCustom/VipsTargetCustom. -// C declarations for the callback bridge between libvips worker threads -// and Go io.Reader/io.Writer instances registered in stream.go. - -#ifndef STREAM_H -#define STREAM_H - -#include "foreign.h" - -// Exported Go callbacks, defined in stream.go via //export. -// Called by the static C trampolines in stream.c. The handle identifies -// an entry in the Go-side callback registry. The buffer/data pointers are -// owned by libvips and are only valid for the duration of the call; Go -// must not retain them. - -// Reads up to length bytes into buffer. Returns bytes read, 0 on EOF, -// -1 on error. -extern gint64 goSourceReadCb(int handle, void *buffer, gint64 length); - -// Seeks the underlying reader. Returns the new absolute offset, or -1 on -// error or if the reader does not support seeking. -extern gint64 goSourceSeekCb(int handle, gint64 offset, int whence); - -// Writes length bytes from data. Returns bytes written, -1 on error. -extern gint64 goTargetWriteCb(int handle, void *data, gint64 length); - -// Signals end of output. Returns 0 on success, -1 on error. -extern int goTargetEndCb(int handle); - -// Creates a VipsSourceCustom with the "read" trampoline connected, and the -// "seek" trampoline too when has_seek is non-zero. The handle is stored as -// signal user_data. Returns a new reference owned by the caller; release -// with clear_source. Returns NULL on failure. -VipsSourceCustom *create_source_custom(int handle, int has_seek); - -// Creates a VipsTargetCustom with the "write" and "end" trampolines -// connected. The handle is stored as signal user_data. Returns a new -// reference owned by the caller; release with clear_target. Returns NULL -// on failure. -VipsTargetCustom *create_target_custom(int handle); - -// Detects the image format by sniffing the source, then loads it. -// Borrows source (does not take ownership). On success returns 0, sets -// params->inputFormat to the detected format, and stores a new VipsImage -// reference in params->outputImage owned by the caller. The image is -// LAZY: it pulls from the source on demand until materialized, so the -// source must stay alive (and registered) until the image is either -// materialized or closed. On failure returns non-zero with the error in -// the vips error buffer. -int load_from_source(VipsSourceCustom *source, LoadParams *params); - -// Returns the decoded (uncompressed) pixel size of in, in bytes. -gint64 image_decoded_size(VipsImage *in); - -// Renders in into a memory image. Borrows in; on success stores a new -// reference in *out owned by the caller. Returns non-zero on failure. -int copy_image_to_memory(VipsImage *in, VipsImage **out); - -// Renders in into the vips-native file at path (one sequential pass), -// then reopens it read-only with random access. Borrows in; on success -// stores a new reference in *out owned by the caller; the caller may -// unlink path immediately (the open file keeps the data alive). -// Returns non-zero on failure. -int write_image_to_disc(VipsImage *in, const char *path, VipsImage **out); - -// Encode params->inputImage to the target. Both the image and the target -// are borrowed (the caller retains ownership). Return 0 on success, -// non-zero on failure with the error in the vips error buffer. -int save_jpeg_to_target(SaveParams *params, VipsTargetCustom *target); -int save_png_to_target(SaveParams *params, VipsTargetCustom *target); -int save_webp_to_target(SaveParams *params, VipsTargetCustom *target); -int save_heif_to_target(SaveParams *params, VipsTargetCustom *target); -int save_gif_to_target(SaveParams *params, VipsTargetCustom *target); - -// Copies the first len bytes of the source into out without consuming -// them (vips_source_sniff buffers and rewinds). Returns non-zero if the -// stream is shorter than len or unreadable. Call before loading so the -// sniff window is still rewindable for every source kind. -int source_sniff_header(VipsSourceCustom *source, unsigned char *out, int len); - -// Unrefs *source / *target and sets it to NULL. NULL-safe. -void clear_source(VipsSourceCustom **source); -void clear_target(VipsTargetCustom **target); - -#endif // STREAM_H diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/test_resources.go b/vendor/github.com/davidbyttow/govips/v2/vips/test_resources.go deleted file mode 100644 index b2e91e4cd3..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/test_resources.go +++ /dev/null @@ -1,6 +0,0 @@ -package vips - -// relative to "/vips/.." -const ( - resources = "../resources/" -) diff --git a/vendor/github.com/davidbyttow/govips/v2/vips/transcode.go b/vendor/github.com/davidbyttow/govips/v2/vips/transcode.go deleted file mode 100644 index d23de1156b..0000000000 --- a/vendor/github.com/davidbyttow/govips/v2/vips/transcode.go +++ /dev/null @@ -1,104 +0,0 @@ -package vips - -import ( - "errors" - "fmt" - "io" -) - -// TranscodeOptions configures TranscodeStream. -type TranscodeOptions struct { - // Format is the output image type. ImageTypeUnknown keeps the - // input format (which must be one of the streaming-save formats: - // JPEG, PNG, WebP, HEIF, TIFF, GIF). - Format ImageType - - // ImportParams configures the load. The Access field is ignored: - // TranscodeStream picks the access mode itself. - ImportParams *ImportParams - - // ExportParams configures the encode; nil uses the format's - // defaults, exactly like SaveToWriter. - ExportParams *ExportParams - - // AutoRotate applies the EXIF orientation to the pixels and clears - // the orientation tag. Orientations that need a non-sequential - // transform (3-8: 180° and 90°/270° families) force the image to be - // materialized first — see the package streaming documentation. - AutoRotate bool -} - -// TranscodeStream decodes an image from r, optionally applies EXIF -// auto-rotation, and encodes it to w in the requested format. Encoded -// bytes are handed to w in chunks as they are produced and are -// byte-identical to the corresponding Export* method with the same -// parameters. -// -// The pipeline picks the cheapest decode strategy automatically: -// -// - Sequential fast path: when no random-access transform is needed -// (AutoRotate false, or EXIF orientation is 1 or 2), pixels flow -// from r to w in one pass. Peak memory is bounded by libvips line -// caches, independent of both file size and pixel count. -// - Materialized path: when AutoRotate requires a rotation, the -// decoded image is first rendered to memory or to an unlinked -// scratch file, depending on its decoded size and the configured -// threshold (SetStreamDiscThreshold, SetStreamScratchDir). -// -// Reader/decode errors (including truncated input) surface from this -// call: on the sequential path during the encode (the first full pass -// over the pixels), on the materialized path during materialization. -// In both cases the original reader/writer error is wrapped and -// matchable with errors.Is. -// -// govips knows nothing about the destination: w is the chunk callback. -// Compose on the consumer side with io.MultiWriter (hash while -// writing), io.Pipe (bridge to reader-shaped sinks), or io.Copy. -func TranscodeStream(r io.Reader, w io.Writer, opts *TranscodeOptions) error { - if r == nil { - return errors.New("transcode: reader is nil") - } - if w == nil { - return errors.New("transcode: writer is nil") - } - if opts == nil { - opts = &TranscodeOptions{} - } - - importParams := NewImportParams() - if opts.ImportParams != nil { - *importParams = *opts.ImportParams - } - importParams.Access.Set(AccessSequential) - - img, err := LoadImageFromReader(r, importParams) - if err != nil { - return fmt.Errorf("transcode: %w", err) - } - defer img.Close() - - if opts.AutoRotate { - // Orientation is header metadata, available before any pixel is - // decoded. Orientations 1 (none) and 2 (horizontal flip) are - // sequential-safe; everything else transposes or reverses line - // order and needs random access. - if img.Orientation() >= 3 { - if err := img.materialize(); err != nil { - return fmt.Errorf("transcode: %w", err) - } - } - if err := img.AutoRotate(); err != nil { - return fmt.Errorf("transcode: autorotate: %w", err) - } - } - - format := opts.Format - if format == ImageTypeUnknown { - format = img.Format() - } - - if err := img.SaveToWriter(w, format, opts.ExportParams); err != nil { - return fmt.Errorf("transcode: %w", err) - } - return nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index ad6f2d9ad0..1919b65a88 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -361,9 +361,6 @@ github.com/cyphar/filepath-securejoin/internal/consts # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew -# github.com/davidbyttow/govips/v2 v2.20.0 -## explicit; go 1.25.0 -github.com/davidbyttow/govips/v2/vips # github.com/deckarep/golang-set v1.8.0 ## explicit; go 1.17 github.com/deckarep/golang-set From c61b1cec8790b321090eff1a34520cc7bda8b675 Mon Sep 17 00:00:00 2001 From: opencloudeu Date: Thu, 12 Nov 2026 23:17:06 +0000 Subject: [PATCH 18/19] [tx] updated from transifex --- .../l10n/locale/sv/LC_MESSAGES/notifications.po | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/services/notifications/pkg/email/l10n/locale/sv/LC_MESSAGES/notifications.po b/services/notifications/pkg/email/l10n/locale/sv/LC_MESSAGES/notifications.po index 0e0e728be0..881d3f27ab 100644 --- a/services/notifications/pkg/email/l10n/locale/sv/LC_MESSAGES/notifications.po +++ b/services/notifications/pkg/email/l10n/locale/sv/LC_MESSAGES/notifications.po @@ -12,7 +12,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: EMAIL\n" -"POT-Creation-Date: 2026-10-27 12:20+0000\n" +"POT-Creation-Date: 2026-11-12 23:16+0000\n" "PO-Revision-Date: 2025-01-27 10:17+0000\n" "Last-Translator: Daniel Nylander , 2026\n" "Language-Team: Swedish (https://app.transifex.com/opencloud-eu/teams/204053/sv/)\n" @@ -60,7 +60,7 @@ msgstr "" #. UnsharedSpace email template, label of the button in the html email #: pkg/email/templates.go:162 msgid "Check access" -msgstr "" +msgstr "Kontrollera åtkomst" #. UnsharedSpace email template, resolves via {{ .CallToAction }} #: pkg/email/templates.go:160 @@ -142,13 +142,13 @@ msgstr "Öppna länk" #. SharedSpace email template, label of the button in the html email #: pkg/email/templates.go:143 msgid "Open space" -msgstr "" +msgstr "Öppna arbetsyta" #. fallbackLinkLabel introduces the plain link below the button of the html #. email #: pkg/email/templates.go:234 msgid "Or open this link:" -msgstr "" +msgstr "Eller öppna den här länken:" #. ScienceMeshInviteTokenGenerated email template, Subject field (resolves #. directly) @@ -166,12 +166,12 @@ msgstr "Delning till '{ShareFolder}' löpte ut {ExpiredAt}" #. Mention email template, label of the button in the html email #: pkg/email/templates.go:244 msgid "View mention" -msgstr "" +msgstr "Visa omnämnande" #. ShareCreated email template, label of the button in the html email #: pkg/email/templates.go:31 msgid "View shares" -msgstr "" +msgstr "Visa delningar" #: pkg/email/templates.go:242 msgid "You can view the mention here: {ResourceLink}" @@ -184,7 +184,7 @@ msgstr "Du nämndes i ”{ResourceName}”" #. GroupedDaily email template, Subject field (resolves directly) #: pkg/email/templates.go:217 msgid "Your daily notifications" -msgstr "" +msgstr "Dina dagliga notiser" #. MembershipExpired email template, resolves via {{ .MessageBody }} #: pkg/email/templates.go:176 @@ -218,7 +218,7 @@ msgstr "" #. GroupedWeekly email template, Subject field (resolves directly) #: pkg/email/templates.go:227 msgid "Your weekly notifications" -msgstr "" +msgstr "Dina veckovisa notiser" #: pkg/email/templates.go:241 msgid "{AuthorName} mentioned you in \"{ResourceName}\"." From c996d22dc475b957f405d80e8732956fb05551cc Mon Sep 17 00:00:00 2001 From: micbar Date: Fri, 13 Nov 2026 09:56:19 +0100 Subject: [PATCH 19/19] chore: add new target branch to backport config --- .backportrc.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.backportrc.json b/.backportrc.json index d724e1c36a..9eee45a731 100644 --- a/.backportrc.json +++ b/.backportrc.json @@ -1,6 +1,6 @@ { "repoOwner": "opencloud-eu", "repoName": "opencloud", - "targetBranchChoices": ["main", "stable-4.0", "stable-7.2" ], + "targetBranchChoices": ["main", "stable-4.0", "stable-7.2", "stable-9.1"], "fork": false }