Search in sources :

Example 1 with InteroperabilityException

use of ch.cyberduck.core.exception.InteroperabilityException in project cyberduck by iterate-ch.

the class BrickWriteFeature method write.

@Override
public HttpResponseOutputStream<FileEntity> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    final String uploadUri;
    FileUploadPartEntity uploadPartEntity = null;
    if (StringUtils.isBlank(status.getUrl())) {
        uploadPartEntity = new BrickUploadFeature(session, this).startUpload(file);
        uploadUri = uploadPartEntity.getUploadUri();
    } else {
        uploadUri = status.getUrl();
    }
    final HttpResponseOutputStream<FileEntity> stream = this.write(file, status, new DelayedHttpEntityCallable<FileEntity>() {

        @Override
        public FileEntity call(final AbstractHttpEntity entity) throws BackgroundException {
            try {
                final HttpPut request = new HttpPut(uploadUri);
                request.setEntity(entity);
                request.setHeader(HttpHeaders.CONTENT_TYPE, MimeTypeService.DEFAULT_CONTENT_TYPE);
                final HttpResponse response = session.getClient().execute(request);
                // Validate response
                try {
                    switch(response.getStatusLine().getStatusCode()) {
                        case HttpStatus.SC_OK:
                            // Upload complete
                            if (response.containsHeader("ETag")) {
                                if (log.isInfoEnabled()) {
                                    log.info(String.format("Received response %s for part number %d", response, status.getPart()));
                                }
                                if (HashAlgorithm.md5.equals(status.getChecksum().algorithm)) {
                                    final Checksum etag = Checksum.parse(StringUtils.remove(response.getFirstHeader("ETag").getValue(), '"'));
                                    if (!status.getChecksum().equals(etag)) {
                                        throw new ChecksumException(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), file.getName()), MessageFormat.format("Mismatch between {0} hash {1} of uploaded data and ETag {2} returned by the server", etag.algorithm.toString(), status.getChecksum().hash, etag.hash));
                                    }
                                }
                                return null;
                            } else {
                                log.error(String.format("Missing ETag in response %s", response));
                                throw new InteroperabilityException(response.getStatusLine().getReasonPhrase());
                            }
                        default:
                            EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity()));
                            throw new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
                    }
                } finally {
                    EntityUtils.consume(response.getEntity());
                }
            } catch (HttpResponseException e) {
                throw new DefaultHttpResponseExceptionMappingService().map(e);
            } catch (IOException e) {
                throw new DefaultIOExceptionMappingService().map(e);
            }
        }

        @Override
        public long getContentLength() {
            return status.getLength();
        }
    });
    if (StringUtils.isBlank(status.getUrl())) {
        final String ref = uploadPartEntity.getRef();
        return new HttpResponseOutputStream<FileEntity>(new ProxyOutputStream(stream), new BrickAttributesFinderFeature(session), status) {

            private final AtomicBoolean close = new AtomicBoolean();

            @Override
            public FileEntity getStatus() throws BackgroundException {
                return stream.getStatus();
            }

            @Override
            public void close() throws IOException {
                if (close.get()) {
                    log.warn(String.format("Skip double close of stream %s", this));
                    return;
                }
                super.close();
                try {
                    new BrickUploadFeature(session, BrickWriteFeature.this).completeUpload(file, ref, status, Collections.singletonList(status));
                } catch (BackgroundException e) {
                    throw new IOException(e.getMessage(), e);
                } finally {
                    close.set(true);
                }
            }
        };
    }
    return stream;
}
Also used : FileEntity(ch.cyberduck.core.brick.io.swagger.client.model.FileEntity) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) ChecksumException(ch.cyberduck.core.exception.ChecksumException) HttpResponse(org.apache.http.HttpResponse) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) FileUploadPartEntity(ch.cyberduck.core.brick.io.swagger.client.model.FileUploadPartEntity) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) Checksum(ch.cyberduck.core.io.Checksum) ProxyOutputStream(org.apache.commons.io.output.ProxyOutputStream) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) HttpResponseOutputStream(ch.cyberduck.core.http.HttpResponseOutputStream) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) BackgroundException(ch.cyberduck.core.exception.BackgroundException)

Example 2 with InteroperabilityException

use of ch.cyberduck.core.exception.InteroperabilityException in project cyberduck by iterate-ch.

the class AbstractUploadFilter method prepare.

@Override
public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Prepare %s", file));
    }
    final TransferStatus status = new TransferStatus().hidden(!hidden.accept(file)).withLockId(parent.getLockId());
    // Read remote attributes first
    if (parent.isExists()) {
        if (find.find(file)) {
            status.setExists(true);
            // Read remote attributes
            final PathAttributes attributes = attribute.find(file);
            status.setRemote(attributes);
        } else {
            // Look if there is directory or file that clashes with this upload
            if (file.getType().contains(Path.Type.file)) {
                if (find.find(new Path(file.getAbsolute(), EnumSet.of(Path.Type.directory)))) {
                    throw new AccessDeniedException(String.format("Cannot replace folder %s with file %s", file.getAbsolute(), local.getName()));
                }
            }
            if (file.getType().contains(Path.Type.directory)) {
                if (find.find(new Path(file.getAbsolute(), EnumSet.of(Path.Type.file)))) {
                    throw new AccessDeniedException(String.format("Cannot replace file %s with folder %s", file.getAbsolute(), local.getName()));
                }
            }
        }
    }
    if (file.isFile()) {
        // Set content length from local file
        if (local.isSymbolicLink()) {
            if (!symlinkResolver.resolve(local)) {
                // Will resolve the symbolic link when the file is requested.
                final Local target = local.getSymlinkTarget();
                status.setLength(target.attributes().getSize());
            }
        // No file size increase for symbolic link to be created on the server
        } else {
            // Read file size from filesystem
            status.setLength(local.attributes().getSize());
        }
        if (options.temporary) {
            final Move feature = session.getFeature(Move.class);
            final Path renamed = new Path(file.getParent(), MessageFormat.format(preferences.getProperty("queue.upload.file.temporary.format"), file.getName(), new AlphanumericRandomStringService().random()), file.getType());
            if (feature.isSupported(file, renamed)) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Set temporary filename %s", renamed));
                }
                status.temporary(renamed, file);
            }
        }
        status.withMime(new MappingMimeTypeService().getMime(file.getName()));
    }
    if (file.isDirectory()) {
        status.setLength(0L);
    }
    if (options.permissions) {
        final UnixPermission feature = session.getFeature(UnixPermission.class);
        if (feature != null) {
            if (status.isExists()) {
                // Already set when reading attributes of file
                status.setPermission(status.getRemote().getPermission());
            } else {
                status.setPermission(feature.getDefault(local));
            }
        } else {
            // Setting target UNIX permissions in transfer status
            status.setPermission(Permission.EMPTY);
        }
    }
    if (options.acl) {
        final AclPermission feature = session.getFeature(AclPermission.class);
        if (feature != null) {
            if (status.isExists()) {
                progress.message(MessageFormat.format(LocaleFactory.localizedString("Getting permission of {0}", "Status"), file.getName()));
                try {
                    status.setAcl(feature.getPermission(file));
                } catch (NotfoundException | AccessDeniedException | InteroperabilityException e) {
                    status.setAcl(feature.getDefault(file, local));
                }
            } else {
                status.setAcl(feature.getDefault(file, local));
            }
        } else {
            // Setting target ACL in transfer status
            status.setAcl(Acl.EMPTY);
        }
    }
    if (options.timestamp) {
        final Timestamp feature = session.getFeature(Timestamp.class);
        if (feature != null) {
            // Read timestamps from local file
            status.setTimestamp(feature.getDefault(local));
        } else {
            if (1L != local.attributes().getModificationDate()) {
                status.setTimestamp(local.attributes().getModificationDate());
            }
        }
    }
    if (options.metadata) {
        final Headers feature = session.getFeature(Headers.class);
        if (feature != null) {
            if (status.isExists()) {
                progress.message(MessageFormat.format(LocaleFactory.localizedString("Reading metadata of {0}", "Status"), file.getName()));
                try {
                    status.setMetadata(feature.getMetadata(file));
                } catch (NotfoundException | AccessDeniedException | InteroperabilityException e) {
                    status.setMetadata(feature.getDefault(local));
                }
            } else {
                status.setMetadata(feature.getDefault(local));
            }
        }
    }
    if (options.encryption) {
        final Encryption feature = session.getFeature(Encryption.class);
        if (feature != null) {
            if (status.isExists()) {
                progress.message(MessageFormat.format(LocaleFactory.localizedString("Reading metadata of {0}", "Status"), file.getName()));
                try {
                    status.setEncryption(feature.getEncryption(file));
                } catch (NotfoundException | AccessDeniedException | InteroperabilityException e) {
                    status.setEncryption(feature.getDefault(file));
                }
            } else {
                status.setEncryption(feature.getDefault(file));
            }
        }
    }
    if (options.redundancy) {
        if (file.isFile()) {
            final Redundancy feature = session.getFeature(Redundancy.class);
            if (feature != null) {
                if (status.isExists()) {
                    progress.message(MessageFormat.format(LocaleFactory.localizedString("Reading metadata of {0}", "Status"), file.getName()));
                    try {
                        status.setStorageClass(feature.getClass(file));
                    } catch (NotfoundException | AccessDeniedException | InteroperabilityException e) {
                        status.setStorageClass(feature.getDefault());
                    }
                } else {
                    status.setStorageClass(feature.getDefault());
                }
            }
        }
    }
    if (options.checksum) {
        if (file.isFile()) {
            final ChecksumCompute feature = session.getFeature(Write.class).checksum(file, status);
            if (feature != null) {
                progress.message(MessageFormat.format(LocaleFactory.localizedString("Calculate checksum for {0}", "Status"), file.getName()));
                try {
                    status.setChecksum(feature.compute(local.getInputStream(), status));
                } catch (LocalAccessDeniedException e) {
                    // Ignore failure reading file when in sandbox when we miss a security scoped access bookmark.
                    // Lock for files is obtained only later in Transfer#pre
                    log.warn(e.getMessage());
                }
            }
        }
    }
    return status;
}
Also used : Path(ch.cyberduck.core.Path) Write(ch.cyberduck.core.features.Write) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) LocalAccessDeniedException(ch.cyberduck.core.exception.LocalAccessDeniedException) LocalNotfoundException(ch.cyberduck.core.exception.LocalNotfoundException) NotfoundException(ch.cyberduck.core.exception.NotfoundException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) Redundancy(ch.cyberduck.core.features.Redundancy) Headers(ch.cyberduck.core.features.Headers) PathAttributes(ch.cyberduck.core.PathAttributes) Local(ch.cyberduck.core.Local) Encryption(ch.cyberduck.core.features.Encryption) Timestamp(ch.cyberduck.core.features.Timestamp) UnixPermission(ch.cyberduck.core.features.UnixPermission) ChecksumCompute(ch.cyberduck.core.io.ChecksumCompute) AclPermission(ch.cyberduck.core.features.AclPermission) Move(ch.cyberduck.core.features.Move) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) AlphanumericRandomStringService(ch.cyberduck.core.AlphanumericRandomStringService) MappingMimeTypeService(ch.cyberduck.core.MappingMimeTypeService) LocalAccessDeniedException(ch.cyberduck.core.exception.LocalAccessDeniedException)

Example 3 with InteroperabilityException

use of ch.cyberduck.core.exception.InteroperabilityException in project cyberduck by iterate-ch.

the class SDSSession method login.

@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final SoftwareVersionData version = this.softwareVersion();
    final Matcher matcher = Pattern.compile(VERSION_REGEX).matcher(version.getRestApiVersion());
    if (matcher.matches()) {
        if (new Version(matcher.group(1)).compareTo(new Version(preferences.getProperty("sds.version.lts"))) < 0) {
            throw new InteroperabilityException(LocaleFactory.localizedString("DRACOON environment needs to be updated", "SDS"), LocaleFactory.localizedString("Your DRACOON environment is outdated and no longer works with this application. Please contact your administrator.", "SDS"));
        }
    }
    final Credentials credentials = host.getCredentials();
    final String login = credentials.getUsername();
    final String password = credentials.getPassword();
    // The provided token is valid for two hours, every usage resets this period to two full hours again. Logging off invalidates the token.
    switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) {
        case oauth:
        case password:
            if ("x-dracoon-action:oauth".equals(CYBERDUCK_REDIRECT_URI)) {
                if (matcher.matches()) {
                    if (new Version(matcher.group(1)).compareTo(new Version("4.15.0")) >= 0) {
                        authorizationService.withRedirectUri(CYBERDUCK_REDIRECT_URI);
                    }
                } else {
                    log.warn(String.format("Failure to parse software version %s", version));
                }
            }
            authorizationService.setTokens(authorizationService.authorize(host, prompt, cancel, SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization()) == SDSProtocol.Authorization.password ? OAuth2AuthorizationService.FlowType.PasswordGrant : OAuth2AuthorizationService.FlowType.AuthorizationCode));
            break;
        case radius:
            final Credentials additional = prompt.prompt(host, LocaleFactory.localizedString("Provide additional login credentials", "Credentials"), LocaleFactory.localizedString("Multi-Factor Authentication", "S3"), new LoginOptions().icon(host.getProtocol().disk()).user(false).keychain(false));
            // Save tokens for 401 error response when expired
            retryHandler.setTokens(login, password, this.login(prompt, new LoginRequest().authType(LoginRequest.AuthTypeEnum.fromValue(host.getProtocol().getAuthorization())).login(login).password(additional.getPassword())));
            break;
        default:
            // Save tokens for 401 error response when expired
            retryHandler.setTokens(login, password, this.login(prompt, new LoginRequest().authType(LoginRequest.AuthTypeEnum.fromValue(host.getProtocol().getAuthorization())).login(login).password(password)));
            break;
    }
    try {
        final UserAccount account = new UserApi(client).requestUserInfo(StringUtils.EMPTY, false, null);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Authenticated as user %s", account));
        }
        switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) {
            case oauth:
                credentials.setUsername(account.getLogin());
                credentials.setSaved(true);
        }
        userAccount.set(new UserAccountWrapper(account));
        requiredKeyPairVersion = this.getRequiredKeyPairVersion();
        this.unlockTripleCryptKeyPair(prompt, userAccount.get(), requiredKeyPairVersion);
    } catch (ApiException e) {
        log.warn(String.format("Ignore failure reading user key pair. %s", new SDSExceptionMappingService(nodeid).map(e)));
    }
}
Also used : InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) Matcher(java.util.regex.Matcher) SoftwareVersionData(ch.cyberduck.core.sds.io.swagger.client.model.SoftwareVersionData) LoginRequest(ch.cyberduck.core.sds.io.swagger.client.model.LoginRequest) UserApi(ch.cyberduck.core.sds.io.swagger.client.api.UserApi) UserAccount(ch.cyberduck.core.sds.io.swagger.client.model.UserAccount) ApiException(ch.cyberduck.core.sds.io.swagger.client.ApiException)

Example 4 with InteroperabilityException

use of ch.cyberduck.core.exception.InteroperabilityException in project cyberduck by iterate-ch.

the class EueSession method login.

@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    try {
        authorizationService.setTokens(authorizationService.refresh(authorizationService.authorize(host, prompt, cancel, OAuth2AuthorizationService.FlowType.AuthorizationCode)));
    } catch (InteroperabilityException e) {
        // Perm.INVALID_GRANT
        log.warn(String.format("Failure %s refreshing OAuth tokens", e));
        // Reset OAuth Tokens
        host.getCredentials().setOauth(OAuthTokens.EMPTY);
        authorizationService.setTokens(authorizationService.authorize(host, prompt, cancel, OAuth2AuthorizationService.FlowType.AuthorizationCode));
    }
    try {
        final StringBuilder url = new StringBuilder();
        url.append(host.getProtocol().getScheme().toString()).append("://");
        url.append(host.getProtocol().getDefaultHostname());
        if (!(host.getProtocol().getScheme().getPort() == host.getPort())) {
            url.append(":").append(host.getPort());
        }
        final String context = PathNormalizer.normalize(host.getProtocol().getContext());
        // Custom authentication context
        url.append(context);
        // Determine RestFS URL from service discovery
        final HttpGet request = new HttpGet(url.toString());
        final CloseableHttpResponse response = client.execute(request);
        switch(response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
                final JsonElement element = JsonParser.parseReader(new InputStreamReader(response.getEntity().getContent()));
                if (element.isJsonObject()) {
                    final JsonObject json = element.getAsJsonObject();
                    final URI uri = URI.create(json.getAsJsonObject("serviceTarget").getAsJsonPrimitive("uri").getAsString());
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Set base path to %s", url));
                    }
                    this.setBasePath(uri.toString());
                }
                break;
            default:
                throw new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
        }
        final Credentials credentials = host.getCredentials();
        credentials.setUsername(new UserInfoApi(new EueApiClient(this)).userinfoGet(null, null).getAccount().getOsServiceId());
        credentials.setSaved(true);
        if (StringUtils.isNotBlank(host.getProperty("pacs.url"))) {
            try {
                client.execute(new HttpPost(host.getProperty("pacs.url")));
            } catch (IOException e) {
                log.warn(String.format("Ignore failure %s running Personal Agent Context Service (PACS) request", e));
            }
        }
        if (StringUtils.isNotBlank(new HostPreferences(host).getProperty("cryptomator.vault.name.default"))) {
            final Path vault = new Path(new HostPreferences(host).getProperty("cryptomator.vault.name.default"), EnumSet.of(Path.Type.directory));
            try {
                vaultResourceId = new EueAttributesFinderFeature(this, resourceid).find(vault).getFileId();
                host.setProperty("cryptomator.enable", String.valueOf(true));
            } catch (NotfoundException e) {
                log.warn(String.format("Disable vault features with no existing vault found at %s", vault));
                // Disable vault features
                host.setProperty("cryptomator.enable", String.valueOf(false));
            }
        }
        userShares.set(this.userShares());
    } catch (ApiException e) {
        throw new EueExceptionMappingService().map(e);
    } catch (HttpResponseException e) {
        throw new DefaultHttpResponseExceptionMappingService().map(e);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : Path(ch.cyberduck.core.Path) HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) NotfoundException(ch.cyberduck.core.exception.NotfoundException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) JsonObject(com.google.gson.JsonObject) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) URI(java.net.URI) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) JsonElement(com.google.gson.JsonElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Credentials(ch.cyberduck.core.Credentials) UserInfoApi(ch.cyberduck.core.eue.io.swagger.client.api.UserInfoApi) ApiException(ch.cyberduck.core.eue.io.swagger.client.ApiException)

Example 5 with InteroperabilityException

use of ch.cyberduck.core.exception.InteroperabilityException in project cyberduck by iterate-ch.

the class FTPAttributesFinderFeatureTest method testAttributesWrongFiletype.

@Test
public void testAttributesWrongFiletype() throws Exception {
    final FTPAttributesFinderFeature f = new FTPAttributesFinderFeature(session);
    final Path file = new FTPTouchFeature(session).touch(new Path(new FTPWorkdirService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file)), new TransferStatus());
    final Attributes attributes = f.find(file);
    assertEquals(0L, attributes.getSize());
    // Test wrong type
    try {
        f.find(new Path(new FTPWorkdirService(session).find(), "test", EnumSet.of(Path.Type.directory)));
        fail();
    } catch (NotfoundException | InteroperabilityException e) {
    // Expected
    }
}
Also used : Path(ch.cyberduck.core.Path) NotfoundException(ch.cyberduck.core.exception.NotfoundException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) Attributes(ch.cyberduck.core.Attributes) PathAttributes(ch.cyberduck.core.PathAttributes) Test(org.junit.Test) IntegrationTest(ch.cyberduck.test.IntegrationTest)

Aggregations

InteroperabilityException (ch.cyberduck.core.exception.InteroperabilityException)56 Path (ch.cyberduck.core.Path)27 AccessDeniedException (ch.cyberduck.core.exception.AccessDeniedException)19 IOException (java.io.IOException)19 NotfoundException (ch.cyberduck.core.exception.NotfoundException)17 BackgroundException (ch.cyberduck.core.exception.BackgroundException)16 TransferStatus (ch.cyberduck.core.transfer.TransferStatus)16 Test (org.junit.Test)12 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)11 IntegrationTest (ch.cyberduck.test.IntegrationTest)10 LoginFailureException (ch.cyberduck.core.exception.LoginFailureException)9 AlphanumericRandomStringService (ch.cyberduck.core.AlphanumericRandomStringService)8 PathAttributes (ch.cyberduck.core.PathAttributes)7 Credentials (ch.cyberduck.core.Credentials)6 ConnectionRefusedException (ch.cyberduck.core.exception.ConnectionRefusedException)6 HostPreferences (ch.cyberduck.core.preferences.HostPreferences)6 ServiceException (org.jets3t.service.ServiceException)6 DisabledListProgressListener (ch.cyberduck.core.DisabledListProgressListener)5 Encryption (ch.cyberduck.core.features.Encryption)5 ArrayList (java.util.ArrayList)5