Search in sources :

Example 6 with PreferencesUseragentProvider

use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.

the class AzureSession method connect.

@Override
protected CloudBlobClient connect(final Proxy proxy, final HostKeyCallback callback, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    try {
        final StorageCredentials credentials;
        if (host.getCredentials().isTokenAuthentication()) {
            credentials = new StorageCredentialsSharedAccessSignature(host.getCredentials().getToken());
        } else {
            credentials = new StorageCredentialsAccountAndKey(host.getCredentials().getUsername(), "null");
        }
        // Client configured with no credentials
        final URI uri = new URI(String.format("%s://%s", Scheme.https, host.getHostname()));
        final CloudBlobClient client = new CloudBlobClient(uri, credentials);
        client.setDirectoryDelimiter(String.valueOf(Path.DELIMITER));
        context.setLoggingEnabled(true);
        context.setLogger(LoggerFactory.getLogger(log.getName()));
        context.setUserHeaders(new HashMap<>(Collections.singletonMap(HttpHeaders.USER_AGENT, new PreferencesUseragentProvider().get())));
        context.getSendingRequestEventHandler().addListener(listener = new StorageEvent<SendingRequestEvent>() {

            @Override
            public void eventOccurred(final SendingRequestEvent event) {
                if (event.getConnectionObject() instanceof HttpsURLConnection) {
                    final HttpsURLConnection connection = (HttpsURLConnection) event.getConnectionObject();
                    connection.setSSLSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key));
                    connection.setHostnameVerifier(new DisabledX509HostnameVerifier());
                }
            }
        });
        switch(proxy.getType()) {
            case SOCKS:
                {
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Configured to use SOCKS proxy %s", proxy));
                    }
                    final java.net.Proxy socksProxy = new java.net.Proxy(java.net.Proxy.Type.SOCKS, new InetSocketAddress(proxy.getHostname(), proxy.getPort()));
                    context.setProxy(socksProxy);
                    break;
                }
            case HTTP:
            case HTTPS:
                {
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Configured to use HTTP proxy %s", proxy));
                    }
                    final java.net.Proxy httpProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostname(), proxy.getPort()));
                    context.setProxy(httpProxy);
                    break;
                }
        }
        return client;
    } catch (URISyntaxException e) {
        throw new LoginFailureException(e.getMessage(), e);
    }
}
Also used : CloudBlobClient(com.microsoft.azure.storage.blob.CloudBlobClient) StorageEvent(com.microsoft.azure.storage.StorageEvent) InetSocketAddress(java.net.InetSocketAddress) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) URISyntaxException(java.net.URISyntaxException) StorageCredentialsAccountAndKey(com.microsoft.azure.storage.StorageCredentialsAccountAndKey) URI(java.net.URI) StorageCredentialsSharedAccessSignature(com.microsoft.azure.storage.StorageCredentialsSharedAccessSignature) StorageCredentials(com.microsoft.azure.storage.StorageCredentials) Proxy(ch.cyberduck.core.proxy.Proxy) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) SendingRequestEvent(com.microsoft.azure.storage.SendingRequestEvent) CustomTrustSSLProtocolSocketFactory(ch.cyberduck.core.ssl.CustomTrustSSLProtocolSocketFactory) DisabledX509HostnameVerifier(ch.cyberduck.core.http.DisabledX509HostnameVerifier) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 7 with PreferencesUseragentProvider

use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.

the class BrickSession method pair.

public Credentials pair(final Host bookmark, final ConnectionCallback alert, final LoginCallback prompt, final CancelCallback cancel, final String title, final String message, final BrowserLauncher browser) throws BackgroundException {
    final String token = new BrickCredentialsConfigurator().configure(host).getToken();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Attempt pairing with token %s", token));
    }
    final BrickPairingSchedulerFeature scheduler = new BrickPairingSchedulerFeature(this, token, bookmark, cancel);
    // Operate in background until canceled
    final ConnectionCallback lock = new DisabledConnectionCallback() {

        final CountDownLatch lock = new CountDownLatch(1);

        @Override
        public void close(final String input) {
            prompt.close(input);
            // Continue with login
            lock.countDown();
        }

        @Override
        public void warn(final Host bookmark, final String title, final String message, final String defaultButton, final String cancelButton, final String preference) throws ConnectionCanceledException {
            alert.warn(bookmark, title, message, defaultButton, cancelButton, preference);
            try {
                final StringBuilder url = new StringBuilder(String.format("%s/login_from_desktop?pairing_key=%s&platform=%s&computer=%s", new HostUrlProvider().withUsername(false).withPath(false).get(host), token, URIEncoder.encode(new PreferencesUseragentProvider().get()), URIEncoder.encode(InetAddress.getLocalHost().getHostName())));
                if (StringUtils.isNotBlank(bookmark.getCredentials().getUsername())) {
                    url.append(String.format("&username=%s", URIEncoder.encode(bookmark.getCredentials().getUsername())));
                }
                if (!browser.open(url.toString())) {
                    throw new ConnectionCanceledException();
                }
            } catch (UnknownHostException e) {
                throw new ConnectionCanceledException(e);
            }
            prompt.await(lock, bookmark, title, message);
            // Check if canceled with null input
            if (StringUtils.isBlank(bookmark.getCredentials().getPassword())) {
                throw new LoginCanceledException();
            }
        }
    };
    // Poll for pairing key until canceled
    scheduler.repeat(lock);
    // Await reply
    try {
        lock.warn(bookmark, title, message, LocaleFactory.localizedString("Login", "Login"), LocaleFactory.localizedString("Cancel"), null);
    } finally {
        // Not canceled
        scheduler.shutdown();
    }
    // When connect attempt is interrupted will throw connection cancel failure
    cancel.verify();
    return bookmark.getCredentials();
}
Also used : HostUrlProvider(ch.cyberduck.core.HostUrlProvider) UnknownHostException(java.net.UnknownHostException) ConnectionCanceledException(ch.cyberduck.core.exception.ConnectionCanceledException) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) Host(ch.cyberduck.core.Host) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) CountDownLatch(java.util.concurrent.CountDownLatch) DisabledConnectionCallback(ch.cyberduck.core.DisabledConnectionCallback) ConnectionCallback(ch.cyberduck.core.ConnectionCallback) DisabledConnectionCallback(ch.cyberduck.core.DisabledConnectionCallback)

Example 8 with PreferencesUseragentProvider

use of ch.cyberduck.core.PreferencesUseragentProvider in project cyberduck by iterate-ch.

the class HttpConnectionPoolBuilder method build.

/**
 * @param proxy    Proxy configuration
 * @param listener Log listener
 * @param prompt   Prompt for proxy credentials
 * @return Builder for HTTP client
 */
public HttpClientBuilder build(final Proxy proxy, final TranscriptListener listener, final LoginCallback prompt) {
    final HttpClientBuilder configuration = HttpClients.custom();
    // relying on internal proxy support in socket factory
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
            if (log.isInfoEnabled()) {
                log.info(String.format("Setup proxy %s", h));
            }
            configuration.setProxy(h);
            configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
            break;
    }
    configuration.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = new HostPreferences(host).getInteger("connection.timeout.seconds") * 1000;
    configuration.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build());
    configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
    configuration.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(new HostPreferences(host).getInteger("http.socket.buffer")).setCharset(Charset.forName(host.getEncoding())).build());
    if (new HostPreferences(host).getBoolean("http.connections.reuse")) {
        configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
    } else {
        configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(new HostPreferences(host).getInteger("http.connections.retry")));
    configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
    if (!new HostPreferences(host).getBoolean("http.compression.enable")) {
        configuration.disableContentCompression();
    }
    configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
    configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName(new HostPreferences(host).getProperty("http.credentials.charset")))).register(AuthSchemes.DIGEST, new DigestSchemeFactory(Charset.forName(new HostPreferences(host).getProperty("http.credentials.charset")))).register(AuthSchemes.NTLM, new HostPreferences(host).getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ? new BackportWindowsNTLMSchemeFactory(null) : new NTLMSchemeFactory()).register(AuthSchemes.SPNEGO, new HostPreferences(host).getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ? new BackportWindowsNegotiateSchemeFactory(null) : new SPNegoSchemeFactory()).register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return configuration;
}
Also used : BasicSchemeFactory(org.apache.http.impl.auth.BasicSchemeFactory) KerberosSchemeFactory(org.apache.http.impl.auth.KerberosSchemeFactory) DefaultClientConnectionReuseStrategy(org.apache.http.impl.client.DefaultClientConnectionReuseStrategy) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) HttpHost(org.apache.http.HttpHost) DigestSchemeFactory(org.apache.http.impl.auth.DigestSchemeFactory) NTLMSchemeFactory(org.apache.http.impl.auth.NTLMSchemeFactory)

Aggregations

PreferencesUseragentProvider (ch.cyberduck.core.PreferencesUseragentProvider)8 UserAgentHttpRequestInitializer (ch.cyberduck.core.http.UserAgentHttpRequestInitializer)4 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)4 OAuth2ErrorResponseInterceptor (ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor)3 OAuth2RequestInterceptor (ch.cyberduck.core.oauth.OAuth2RequestInterceptor)3 HostPreferences (ch.cyberduck.core.preferences.HostPreferences)3 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)2 HostUrlProvider (ch.cyberduck.core.HostUrlProvider)2 UseragentProvider (ch.cyberduck.core.UseragentProvider)2 LoginCanceledException (ch.cyberduck.core.exception.LoginCanceledException)2 DefaultHttpResponseExceptionMappingService (ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService)2 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)2 TokenResponseException (com.google.api.client.auth.oauth2.TokenResponseException)2 GenericUrl (com.google.api.client.http.GenericUrl)2 HttpResponseException (com.google.api.client.http.HttpResponseException)2 ApacheHttpTransport (com.google.api.client.http.apache.v2.ApacheHttpTransport)2 GsonFactory (com.google.api.client.json.gson.GsonFactory)2 IOException (java.io.IOException)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AlphanumericRandomStringService (ch.cyberduck.core.AlphanumericRandomStringService)1