Search in sources :

Example 1 with HostPreferences

use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.

the class BrickPairingSchedulerFeature method repeat.

public void repeat(final PasswordCallback callback) {
    final long timeout = new HostPreferences(session.getHost()).getLong("brick.pairing.interrupt.ms");
    final long start = System.currentTimeMillis();
    scheduler.repeat(() -> {
        try {
            if (System.currentTimeMillis() - start > timeout) {
                throw new ConnectionCanceledException(String.format("Interrupt polling for pairing key after %d", timeout));
            }
            this.operate(callback);
        } catch (ConnectionCanceledException e) {
            log.warn(String.format("Cancel processing scheduled task. %s", e.getMessage()), e);
            callback.close(null);
            this.shutdown();
        } catch (BackgroundException e) {
            log.warn(String.format("Failure processing scheduled task. %s", e.getMessage()), e);
            callback.close(null);
            this.shutdown();
        }
    }, new HostPreferences(session.getHost()).getLong("brick.pairing.interval.ms"), TimeUnit.MILLISECONDS);
}
Also used : ConnectionCanceledException(ch.cyberduck.core.exception.ConnectionCanceledException) BackgroundException(ch.cyberduck.core.exception.BackgroundException) HostPreferences(ch.cyberduck.core.preferences.HostPreferences)

Example 2 with HostPreferences

use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.

the class BrickPairingSchedulerFeature method operate.

/**
 * Pool for pairing key from service
 *
 * @param callback Callback when service returns 200
 */
private void operate(final PasswordCallback callback) throws BackgroundException {
    try {
        final HttpPost resource = new HttpPost(String.format("%s/api/rest/v1/sessions/pairing_key/%s", new HostUrlProvider().withUsername(false).withPath(false).get(session.getHost()), token));
        resource.setHeader(HttpHeaders.ACCEPT, "application/json");
        resource.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        if (log.isInfoEnabled()) {
            log.info(String.format("Fetch credentials for paring key %s from %s", token, resource));
        }
        final JsonObject json = session.getClient().execute(resource, new AbstractResponseHandler<JsonObject>() {

            @Override
            public JsonObject handleEntity(final HttpEntity entity) throws IOException {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copy(entity.getContent(), out);
                return JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))).getAsJsonObject();
            }
        });
        if (json.has("nickname")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.nickname.configure")) {
                final JsonPrimitive nickname = json.getAsJsonPrimitive("nickname");
                if (StringUtils.isNotBlank(host.getNickname())) {
                    if (!StringUtils.equals(host.getNickname(), nickname.getAsString())) {
                        log.warn(String.format("Mismatch of nickname. Previously authorized as %s and now paired as %s", host.getNickname(), nickname.getAsString()));
                        callback.close(null);
                        throw new LoginCanceledException();
                    }
                }
                host.setNickname(nickname.getAsString());
            }
        }
        final Credentials credentials = host.getCredentials();
        if (json.has("user_username")) {
            credentials.setUsername(json.getAsJsonPrimitive("user_username").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("password")) {
            credentials.setPassword(json.getAsJsonPrimitive("password").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("server")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.hostname.configure")) {
                host.setHostname(URI.create(json.getAsJsonPrimitive("server").getAsString()).getHost());
            }
        }
        callback.close(credentials.getUsername());
    } catch (JsonParseException e) {
        throw new DefaultIOExceptionMappingService().map(new IOException(e.getMessage(), e));
    } catch (HttpResponseException e) {
        switch(e.getStatusCode()) {
            case HttpStatus.SC_NOT_FOUND:
                log.warn(String.format("Missing login for pairing key %s", token));
                cancel.verify();
                break;
            default:
                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) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) JsonPrimitive(com.google.gson.JsonPrimitive) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) JsonObject(com.google.gson.JsonObject) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.google.gson.JsonParseException) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Credentials(ch.cyberduck.core.Credentials)

Example 3 with HostPreferences

use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.

the class SDSMissingFileKeysSchedulerFeature method deleteDeprecatedKeyPair.

private void deleteDeprecatedKeyPair(final SDSSession session) throws ApiException, BackgroundException {
    if (new HostPreferences(session.getHost()).getBoolean("sds.encryption.missingkeys.delete.deprecated")) {
        if (session.keyPairDeprecated() != null && !session.keyPairDeprecated().equals(session.keyPair())) {
            final MissingKeysResponse missingKeys = new NodesApi(session.getClient()).requestMissingFileKeys(null, 1, null, null, session.userAccount().getId(), "previous_user_key", null);
            if (missingKeys.getItems().isEmpty()) {
                log.debug("No more deprecated fileKeys to migrate - deleting deprecated key pair");
                new UserApi(session.getClient()).removeUserKeyPair(session.keyPairDeprecated().getPublicKeyContainer().getVersion(), null);
                session.resetUserKeyPairs();
            }
        }
    }
}
Also used : NodesApi(ch.cyberduck.core.sds.io.swagger.client.api.NodesApi) MissingKeysResponse(ch.cyberduck.core.sds.io.swagger.client.model.MissingKeysResponse) UserApi(ch.cyberduck.core.sds.io.swagger.client.api.UserApi) HostPreferences(ch.cyberduck.core.preferences.HostPreferences)

Example 4 with HostPreferences

use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.

the class SDSMoveFeature method move.

@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
    try {
        final long nodeId = Long.parseLong(nodeid.getVersionId(file, new DisabledListProgressListener()));
        if (containerService.isContainer(file)) {
            final Node node = new NodesApi(session.getClient()).updateRoom(new UpdateRoomRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
            nodeid.cache(renamed, file.attributes().getVersionId());
            nodeid.cache(file, null);
            return renamed.withAttributes(new SDSAttributesAdapter(session).toAttributes(node));
        } else {
            if (status.isExists()) {
                // Handle case insensitive. Find feature will have reported target to exist if same name with different case
                if (!new CaseInsensitivePathPredicate(file).test(renamed)) {
                    log.warn(String.format("Delete existing file %s", renamed));
                    new SDSDeleteFeature(session, nodeid).delete(Collections.singletonMap(renamed, status), connectionCallback, callback);
                }
            }
            if (new SimplePathPredicate(file.getParent()).test(renamed.getParent())) {
                // Rename only
                if (file.isDirectory()) {
                    new NodesApi(session.getClient()).updateFolder(new UpdateFolderRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
                } else {
                    new NodesApi(session.getClient()).updateFile(new UpdateFileRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
                }
            } else {
                // Move to different parent
                new NodesApi(session.getClient()).moveNodes(new MoveNodesRequest().resolutionStrategy(MoveNodesRequest.ResolutionStrategyEnum.OVERWRITE).addItemsItem(new MoveNode().id(nodeId).name(renamed.getName())).keepShareLinks(new HostPreferences(session.getHost()).getBoolean("sds.upload.sharelinks.keep")), Long.parseLong(nodeid.getVersionId(renamed.getParent(), new DisabledListProgressListener())), StringUtils.EMPTY, null);
            }
            nodeid.cache(renamed, file.attributes().getVersionId());
            nodeid.cache(file, null);
            // Copy original file attributes
            return renamed.withAttributes(new PathAttributes(file.attributes()).withVersionId(String.valueOf(nodeId)));
        }
    } catch (ApiException e) {
        throw new SDSExceptionMappingService(nodeid).map("Cannot rename {0}", e, file);
    }
}
Also used : CaseInsensitivePathPredicate(ch.cyberduck.core.CaseInsensitivePathPredicate) DisabledListProgressListener(ch.cyberduck.core.DisabledListProgressListener) Node(ch.cyberduck.core.sds.io.swagger.client.model.Node) MoveNode(ch.cyberduck.core.sds.io.swagger.client.model.MoveNode) PathAttributes(ch.cyberduck.core.PathAttributes) MoveNode(ch.cyberduck.core.sds.io.swagger.client.model.MoveNode) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) NodesApi(ch.cyberduck.core.sds.io.swagger.client.api.NodesApi) UpdateRoomRequest(ch.cyberduck.core.sds.io.swagger.client.model.UpdateRoomRequest) MoveNodesRequest(ch.cyberduck.core.sds.io.swagger.client.model.MoveNodesRequest) SimplePathPredicate(ch.cyberduck.core.SimplePathPredicate) UpdateFileRequest(ch.cyberduck.core.sds.io.swagger.client.model.UpdateFileRequest) UpdateFolderRequest(ch.cyberduck.core.sds.io.swagger.client.model.UpdateFolderRequest) ApiException(ch.cyberduck.core.sds.io.swagger.client.ApiException)

Example 5 with HostPreferences

use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.

the class SDSDirectS3MultipartWriteFeatureTest method testWriteEncrypted.

@Test
public void testWriteEncrypted() throws Exception {
    final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
    final Path room = new SDSDirectoryFeature(session, nodeid).createRoom(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), true);
    final byte[] content = RandomUtils.nextBytes(new HostPreferences(session.getHost()).getInteger("sds.upload.multipart.chunksize") + 1);
    final Path test = new Path(room, new NFDNormalizer().normalize(String.format("รค%s", new AlphanumericRandomStringService().random())).toString(), EnumSet.of(Path.Type.file));
    {
        final TripleCryptWriteFeature writer = new TripleCryptWriteFeature(session, nodeid, new SDSDirectS3MultipartWriteFeature(session, nodeid));
        final TransferStatus status = new TransferStatus();
        status.setLength(content.length);
        status.setChecksum(new MD5ChecksumCompute().compute(new ByteArrayInputStream(content), new TransferStatus()));
        status.setTimestamp(1632127025217L);
        final StatusOutputStream<Node> out = writer.write(test, status, new DisabledConnectionCallback());
        assertNotNull(out);
        new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out);
    }
    assertNotNull(test.attributes().getVersionId());
    assertTrue(new DefaultFindFeature(session).find(test));
    assertTrue(new SDSFindFeature(session, nodeid).find(test));
    final PathAttributes attr = new SDSAttributesFinderFeature(session, nodeid).find(test);
    assertEquals(test.attributes().getVersionId(), attr.getVersionId());
    assertEquals(1632127025217L, attr.getModificationDate());
    assertEquals(1632127025217L, new DefaultAttributesFinderFeature(session).find(test).getModificationDate());
    final byte[] compare = new byte[content.length];
    final InputStream stream = new TripleCryptReadFeature(session, nodeid, new SDSReadFeature(session, nodeid)).read(test, new TransferStatus().withLength(content.length), new DisabledConnectionCallback() {

        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) {
            return new VaultCredentials("eth[oh8uv4Eesij");
        }
    });
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    String previousVersion = test.attributes().getVersionId();
    // Overwrite
    {
        final byte[] change = RandomUtils.nextBytes(256);
        final TransferStatus status = new TransferStatus();
        status.setLength(change.length);
        final TripleCryptWriteFeature writer = new TripleCryptWriteFeature(session, nodeid, new SDSDirectS3MultipartWriteFeature(session, nodeid));
        final StatusOutputStream<Node> out = writer.write(test, status.exists(true), new DisabledConnectionCallback());
        assertNotNull(out);
        new StreamCopier(status, status).transfer(new ByteArrayInputStream(change), out);
        assertNotEquals(test.attributes().getVersionId(), out.getStatus());
    }
    assertNotEquals(attr.getRevision(), new SDSAttributesFinderFeature(session, nodeid).find(test));
    // Read with previous version must fail
    try {
        test.attributes().withVersionId(previousVersion);
        new TripleCryptReadFeature(session, nodeid, new SDSReadFeature(session, nodeid)).read(test, new TransferStatus(), new DisabledConnectionCallback() {

            @Override
            public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) {
                return new VaultCredentials("eth[oh8uv4Eesij");
            }
        });
        fail();
    } catch (NotfoundException e) {
    // Expected
    }
    new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
Also used : Delete(ch.cyberduck.core.features.Delete) LoginOptions(ch.cyberduck.core.LoginOptions) DefaultFindFeature(ch.cyberduck.core.shared.DefaultFindFeature) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) TripleCryptWriteFeature(ch.cyberduck.core.sds.triplecrypt.TripleCryptWriteFeature) Path(ch.cyberduck.core.Path) NotfoundException(ch.cyberduck.core.exception.NotfoundException) VaultCredentials(ch.cyberduck.core.vault.VaultCredentials) StatusOutputStream(ch.cyberduck.core.io.StatusOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PathAttributes(ch.cyberduck.core.PathAttributes) Host(ch.cyberduck.core.Host) TripleCryptReadFeature(ch.cyberduck.core.sds.triplecrypt.TripleCryptReadFeature) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) MD5ChecksumCompute(ch.cyberduck.core.io.MD5ChecksumCompute) NFDNormalizer(ch.cyberduck.core.unicode.NFDNormalizer) DefaultAttributesFinderFeature(ch.cyberduck.core.shared.DefaultAttributesFinderFeature) ByteArrayInputStream(java.io.ByteArrayInputStream) DisabledLoginCallback(ch.cyberduck.core.DisabledLoginCallback) AlphanumericRandomStringService(ch.cyberduck.core.AlphanumericRandomStringService) DisabledConnectionCallback(ch.cyberduck.core.DisabledConnectionCallback) StreamCopier(ch.cyberduck.core.io.StreamCopier) VaultCredentials(ch.cyberduck.core.vault.VaultCredentials) Credentials(ch.cyberduck.core.Credentials) Test(org.junit.Test) IntegrationTest(ch.cyberduck.test.IntegrationTest)

Aggregations

HostPreferences (ch.cyberduck.core.preferences.HostPreferences)81 IOException (java.io.IOException)33 Path (ch.cyberduck.core.Path)29 DisabledListProgressListener (ch.cyberduck.core.DisabledListProgressListener)18 BackgroundException (ch.cyberduck.core.exception.BackgroundException)12 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)11 PathAttributes (ch.cyberduck.core.PathAttributes)11 NotfoundException (ch.cyberduck.core.exception.NotfoundException)11 File (com.google.api.services.drive.model.File)10 AttributedList (ch.cyberduck.core.AttributedList)8 URI (java.net.URI)8 TransferStatus (ch.cyberduck.core.transfer.TransferStatus)7 AlphanumericRandomStringService (ch.cyberduck.core.AlphanumericRandomStringService)6 SimplePathPredicate (ch.cyberduck.core.SimplePathPredicate)6 InteroperabilityException (ch.cyberduck.core.exception.InteroperabilityException)6 MemorySegementingOutputStream (ch.cyberduck.core.io.MemorySegementingOutputStream)6 NodesApi (ch.cyberduck.core.sds.io.swagger.client.api.NodesApi)5 Credentials (ch.cyberduck.core.Credentials)4 Partition (ch.cyberduck.core.collections.Partition)4 S3Protocol (ch.cyberduck.core.s3.S3Protocol)4