Search in sources :

Example 1 with DelegatingHomeFeature

use of ch.cyberduck.core.shared.DelegatingHomeFeature in project cyberduck by iterate-ch.

the class NextcloudShareProvider method toDownloadUrl.

/**
 * int) 0 = user; 1 = group; 3 = public link; 6 = federated cloud share
 */
@Override
public DescriptiveUrl toDownloadUrl(final Path file, final Object options, final PasswordCallback callback) throws BackgroundException {
    final Host bookmark = session.getHost();
    final StringBuilder request = new StringBuilder(String.format("https://%s/ocs/v2.php/apps/files_sharing/api/v1/shares?path=%s&shareType=%d", bookmark.getHostname(), URIEncoder.encode(StringUtils.substringAfter(file.getAbsolute(), new DelegatingHomeFeature(new DefaultPathHomeFeature(session.getHost()), session.getFeature(Home.class)).find().getAbsolute())), // Public link
    3));
    try {
        request.append(String.format("&password=%s", callback.prompt(bookmark, LocaleFactory.localizedString("Passphrase", "Cryptomator"), MessageFormat.format(LocaleFactory.localizedString("Create a passphrase required to access {0}", "Credentials"), file.getName()), new LoginOptions().keychain(false).icon(bookmark.getProtocol().disk())).getPassword()));
    } catch (LoginCanceledException e) {
    // Ignore no password set
    }
    final HttpPost resource = new HttpPost(request.toString());
    resource.setHeader("OCS-APIRequest", "true");
    resource.setHeader(HttpHeaders.ACCEPT, "application/xml");
    try {
        return new DescriptiveUrl(session.getClient().execute(resource, new AbstractResponseHandler<URI>() {

            @Override
            public URI handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
                final StatusLine statusLine = response.getStatusLine();
                final HttpEntity entity = response.getEntity();
                if (statusLine.getStatusCode() >= 300) {
                    final StringAppender message = new StringAppender();
                    message.append(statusLine.getReasonPhrase());
                    final ocs error = new XmlMapper().readValue(entity.getContent(), ocs.class);
                    message.append(error.meta.message);
                    throw new HttpResponseException(statusLine.getStatusCode(), message.toString());
                }
                return super.handleResponse(response);
            }

            @Override
            public URI handleEntity(final HttpEntity entity) throws IOException {
                final XmlMapper mapper = new XmlMapper();
                ocs value = mapper.readValue(entity.getContent(), ocs.class);
                return URI.create(value.data.url);
            }
        }), DescriptiveUrl.Type.http);
    } catch (HttpResponseException e) {
        throw new DefaultHttpResponseExceptionMappingService().map(e);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) HttpEntity(org.apache.http.HttpEntity) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) HttpResponse(org.apache.http.HttpResponse) Host(ch.cyberduck.core.Host) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) LoginOptions(ch.cyberduck.core.LoginOptions) StatusLine(org.apache.http.StatusLine) DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) AbstractResponseHandler(org.apache.http.impl.client.AbstractResponseHandler) StringAppender(ch.cyberduck.core.StringAppender) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Home(ch.cyberduck.core.features.Home)

Example 2 with DelegatingHomeFeature

use of ch.cyberduck.core.shared.DelegatingHomeFeature in project cyberduck by iterate-ch.

the class S3Session method login.

@Override
public void login(final Proxy proxy, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    if (Scheme.isURL(host.getProtocol().getContext())) {
        try {
            final Credentials temporary = new AWSSessionCredentialsRetriever(trust, key, this, host.getProtocol().getContext()).get();
            client.setProviderCredentials(new AWSSessionCredentials(temporary.getUsername(), temporary.getPassword(), temporary.getToken()));
        } catch (ConnectionTimeoutException | ConnectionRefusedException | ResolveFailedException | NotfoundException | InteroperabilityException e) {
            log.warn(String.format("Failure to retrieve session credentials from . %s", e.getMessage()));
            throw new LoginFailureException(e.getDetail(false), e);
        }
    } else {
        final Credentials credentials;
        // Only for AWS
        if (isAwsHostname(host.getHostname())) {
            // Try auto-configure
            credentials = new STSCredentialsConfigurator(new ThreadLocalHostnameDelegatingTrustManager(trust, host.getHostname()), key, prompt).configure(host);
        } else {
            credentials = host.getCredentials();
        }
        if (StringUtils.isNotBlank(credentials.getToken())) {
            client.setProviderCredentials(credentials.isAnonymousLogin() ? null : new AWSSessionCredentials(credentials.getUsername(), credentials.getPassword(), credentials.getToken()));
        } else {
            client.setProviderCredentials(credentials.isAnonymousLogin() ? null : new AWSCredentials(credentials.getUsername(), credentials.getPassword()));
        }
    }
    if (host.getCredentials().isPassed()) {
        log.warn(String.format("Skip verifying credentials with previous successful authentication event for %s", this));
        return;
    }
    try {
        final Location.Name location = new S3PathStyleFallbackAdapter<>(this, new BackgroundExceptionCallable<Location.Name>() {

            @Override
            public Location.Name call() throws BackgroundException {
                return new S3LocationFeature(S3Session.this, client.getRegionEndpointCache()).getLocation(new DelegatingHomeFeature(new DefaultPathHomeFeature(host)).find());
            }
        }).call();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Retrieved region %s", location));
        }
        if (!Location.unknown.equals(location)) {
            client.getConfiguration().setProperty("storage-service.default-region", location.getIdentifier());
        }
    } catch (AccessDeniedException | InteroperabilityException e) {
        log.warn(String.format("Failure %s querying region", e));
        final Path home = new DefaultHomeFinderService(this).find();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Retrieved %s", home));
        }
    }
}
Also used : Path(ch.cyberduck.core.Path) NotfoundException(ch.cyberduck.core.exception.NotfoundException) AccessDeniedException(ch.cyberduck.core.exception.AccessDeniedException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) DefaultHomeFinderService(ch.cyberduck.core.shared.DefaultHomeFinderService) ConnectionRefusedException(ch.cyberduck.core.exception.ConnectionRefusedException) ResolveFailedException(ch.cyberduck.core.exception.ResolveFailedException) AWSCredentials(org.jets3t.service.security.AWSCredentials) BackgroundExceptionCallable(ch.cyberduck.core.threading.BackgroundExceptionCallable) ConnectionTimeoutException(ch.cyberduck.core.exception.ConnectionTimeoutException) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) AWSSessionCredentials(org.jets3t.service.security.AWSSessionCredentials) ThreadLocalHostnameDelegatingTrustManager(ch.cyberduck.core.ssl.ThreadLocalHostnameDelegatingTrustManager) AWSSessionCredentialsRetriever(ch.cyberduck.core.auth.AWSSessionCredentialsRetriever) AWSCredentials(org.jets3t.service.security.AWSCredentials) Credentials(ch.cyberduck.core.Credentials) AWSSessionCredentials(org.jets3t.service.security.AWSSessionCredentials) STSCredentialsConfigurator(ch.cyberduck.core.sts.STSCredentialsConfigurator)

Example 3 with DelegatingHomeFeature

use of ch.cyberduck.core.shared.DelegatingHomeFeature in project cyberduck by iterate-ch.

the class RemoteProfilesFinder method find.

@Override
public Set<ProfileDescription> find(final Visitor visitor) throws BackgroundException {
    if (log.isInfoEnabled()) {
        log.info(String.format("Fetch profiles from %s", session.getHost()));
    }
    final ProfileFilter filter = new ProfileFilter();
    final AttributedList<Path> list = session.getFeature(ListService.class).list(new DelegatingHomeFeature(new DefaultPathHomeFeature(session.getHost())).find(), new DisabledListProgressListener());
    return list.filter(filter).toStream().map(file -> visitor.visit(new RemoteProfileDescription(protocols, file, new LazyInitializer<Local>() {

        @Override
        protected Local initialize() throws ConcurrentException {
            try {
                final Read read = session.getFeature(Read.class);
                if (log.isInfoEnabled()) {
                    log.info(String.format("Download profile %s", file));
                }
                final InputStream in = read.read(file.withAttributes(new PathAttributes(file.attributes()).withVersionId(null)), new TransferStatus().withLength(TransferStatus.UNKNOWN_LENGTH), new DisabledConnectionCallback());
                final Local temp = TemporaryFileServiceFactory.get().create(file.getName());
                new DefaultLocalTouchFeature().touch(temp);
                final OutputStream out = temp.getOutputStream(false);
                try {
                    IOUtils.copy(in, out);
                } finally {
                    in.close();
                    out.close();
                }
                return temp;
            } catch (BackgroundException | IOException e) {
                throw new ConcurrentException(e);
            }
        }
    }))).collect(Collectors.toSet());
}
Also used : Path(ch.cyberduck.core.Path) Read(ch.cyberduck.core.features.Read) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) DefaultLocalTouchFeature(ch.cyberduck.core.local.DefaultLocalTouchFeature) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) ListService(ch.cyberduck.core.ListService) TemporaryFileServiceFactory(ch.cyberduck.core.local.TemporaryFileServiceFactory) ProtocolFactory(ch.cyberduck.core.ProtocolFactory) Filter(ch.cyberduck.core.Filter) Local(ch.cyberduck.core.Local) ConcurrentException(org.apache.commons.lang3.concurrent.ConcurrentException) DisabledConnectionCallback(ch.cyberduck.core.DisabledConnectionCallback) PathAttributes(ch.cyberduck.core.PathAttributes) OutputStream(java.io.OutputStream) Session(ch.cyberduck.core.Session) AttributedList(ch.cyberduck.core.AttributedList) Set(java.util.Set) IOException(java.io.IOException) DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) BackgroundException(ch.cyberduck.core.exception.BackgroundException) Collectors(java.util.stream.Collectors) LazyInitializer(org.apache.commons.lang3.concurrent.LazyInitializer) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) IOUtils(org.apache.commons.io.IOUtils) Logger(org.apache.logging.log4j.Logger) Path(ch.cyberduck.core.Path) Pattern(java.util.regex.Pattern) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) LazyInitializer(org.apache.commons.lang3.concurrent.LazyInitializer) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) InputStream(java.io.InputStream) PathAttributes(ch.cyberduck.core.PathAttributes) OutputStream(java.io.OutputStream) Local(ch.cyberduck.core.Local) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) IOException(java.io.IOException) ListService(ch.cyberduck.core.ListService) Read(ch.cyberduck.core.features.Read) DefaultLocalTouchFeature(ch.cyberduck.core.local.DefaultLocalTouchFeature) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) DisabledConnectionCallback(ch.cyberduck.core.DisabledConnectionCallback) BackgroundException(ch.cyberduck.core.exception.BackgroundException) ConcurrentException(org.apache.commons.lang3.concurrent.ConcurrentException)

Example 4 with DelegatingHomeFeature

use of ch.cyberduck.core.shared.DelegatingHomeFeature in project cyberduck by iterate-ch.

the class DAVSession method alert.

@Override
public boolean alert(final ConnectionCallback callback) throws BackgroundException {
    if (super.alert(callback)) {
        // Propose protocol change if HEAD request redirects to HTTPS
        final Path home = new DelegatingHomeFeature(new DefaultPathHomeFeature(host)).find();
        try {
            final RequestConfig context = client.context().getRequestConfig();
            final HttpHead request = new HttpHead(new DAVPathEncoder().encode(home));
            request.setConfig(RequestConfig.copy(context).setRedirectsEnabled(false).build());
            final Header location = client.execute(request, new ValidatingResponseHandler<Header>() {

                @Override
                public Header handleResponse(final HttpResponse response) {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) {
                        return response.getFirstHeader(HttpHeaders.LOCATION);
                    }
                    return null;
                }
            });
            // Reset default redirect configuration in context
            client.context().setRequestConfig(RequestConfig.copy(context).setRedirectsEnabled(true).build());
            if (null != location) {
                final URL url = new URL(location.getValue());
                if (StringUtils.equals(Scheme.https.name(), url.getProtocol())) {
                    try {
                        callback.warn(host, MessageFormat.format(LocaleFactory.localizedString("Unsecured {0} connection", "Credentials"), host.getProtocol().getName()), MessageFormat.format("{0} {1}.", MessageFormat.format(LocaleFactory.localizedString("The server supports encrypted connections. Do you want to switch to {0}?", "Credentials"), new DAVSSLProtocol().getName()), LocaleFactory.localizedString("Please contact your web hosting service provider for assistance", "Support")), LocaleFactory.localizedString("Continue", "Credentials"), LocaleFactory.localizedString("Change", "Credentials"), String.format("connection.unsecure.%s", host.getHostname()));
                    // Continue chosen. Login using plain FTP.
                    } catch (LoginCanceledException e) {
                        // Protocol switch
                        host.setHostname(url.getHost());
                        host.setProtocol(ProtocolFactory.get().forScheme(Scheme.davs));
                        return false;
                    }
                }
            }
        // Continue with default alert
        } catch (SardineException e) {
            // Ignore failure
            log.warn(String.format("Ignore failed HEAD request to %s with %s.", host, e.getResponsePhrase()));
        } catch (IOException e) {
            throw new HttpExceptionMappingService().map(e);
        }
        return preferences.getBoolean("webdav.basic.preemptive");
    }
    return false;
}
Also used : Path(ch.cyberduck.core.Path) RequestConfig(org.apache.http.client.config.RequestConfig) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) HttpResponse(org.apache.http.HttpResponse) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) IOException(java.io.IOException) HttpHead(org.apache.http.client.methods.HttpHead) URL(java.net.URL) SardineException(com.github.sardine.impl.SardineException) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) Header(org.apache.http.Header)

Example 5 with DelegatingHomeFeature

use of ch.cyberduck.core.shared.DelegatingHomeFeature in project cyberduck by iterate-ch.

the class NextcloudShareProvider method toUploadUrl.

@Override
public DescriptiveUrl toUploadUrl(final Path file, final Object options, final PasswordCallback callback) throws BackgroundException {
    final Host bookmark = session.getHost();
    final StringBuilder request = new StringBuilder(String.format("https://%s/ocs/v2.php/apps/files_sharing/api/v1/shares?path=%s&shareType=%d&publicUpload=true", bookmark.getHostname(), URIEncoder.encode(StringUtils.substringAfter(file.getAbsolute(), new DelegatingHomeFeature(new DefaultPathHomeFeature(session.getHost()), session.getFeature(Home.class)).find().getAbsolute())), // Public link
    3));
    try {
        request.append(String.format("&password=%s", callback.prompt(bookmark, LocaleFactory.localizedString("Passphrase", "Cryptomator"), MessageFormat.format(LocaleFactory.localizedString("Create a passphrase required to access {0}", "Credentials"), file.getName()), new LoginOptions().keychain(false).icon(bookmark.getProtocol().disk())).getPassword()));
    } catch (LoginCanceledException e) {
    // Ignore no password set
    }
    final HttpPost resource = new HttpPost(request.toString());
    resource.setHeader("OCS-APIRequest", "true");
    resource.setHeader(HttpHeaders.ACCEPT, "application/xml");
    try {
        return new DescriptiveUrl(session.getClient().execute(resource, new AbstractResponseHandler<URI>() {

            @Override
            public URI handleEntity(final HttpEntity entity) throws IOException {
                final XmlMapper mapper = new XmlMapper();
                ocs value = mapper.readValue(entity.getContent(), ocs.class);
                return URI.create(value.data.url);
            }
        }), DescriptiveUrl.Type.http);
    } catch (HttpResponseException e) {
        throw new DefaultHttpResponseExceptionMappingService().map(e);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) DelegatingHomeFeature(ch.cyberduck.core.shared.DelegatingHomeFeature) HttpEntity(org.apache.http.HttpEntity) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) Host(ch.cyberduck.core.Host) DefaultPathHomeFeature(ch.cyberduck.core.shared.DefaultPathHomeFeature) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) LoginOptions(ch.cyberduck.core.LoginOptions) DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) AbstractResponseHandler(org.apache.http.impl.client.AbstractResponseHandler) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Home(ch.cyberduck.core.features.Home)

Aggregations

DefaultPathHomeFeature (ch.cyberduck.core.shared.DefaultPathHomeFeature)6 DelegatingHomeFeature (ch.cyberduck.core.shared.DelegatingHomeFeature)6 IOException (java.io.IOException)5 Path (ch.cyberduck.core.Path)4 LoginCanceledException (ch.cyberduck.core.exception.LoginCanceledException)3 AttributedList (ch.cyberduck.core.AttributedList)2 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)2 DescriptiveUrl (ch.cyberduck.core.DescriptiveUrl)2 DisabledListProgressListener (ch.cyberduck.core.DisabledListProgressListener)2 Host (ch.cyberduck.core.Host)2 LoginOptions (ch.cyberduck.core.LoginOptions)2 Home (ch.cyberduck.core.features.Home)2 DefaultHttpResponseExceptionMappingService (ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService)2 HttpExceptionMappingService (ch.cyberduck.core.http.HttpExceptionMappingService)2 HttpResponse (org.apache.http.HttpResponse)2 Credentials (ch.cyberduck.core.Credentials)1 DisabledConnectionCallback (ch.cyberduck.core.DisabledConnectionCallback)1 Filter (ch.cyberduck.core.Filter)1 ListService (ch.cyberduck.core.ListService)1 Local (ch.cyberduck.core.Local)1