public FTPSNetworkClient(final String host, final int port){ client = new FTPSClient(); this.host = host; this.port = port; this.username = "anonymous"; this.password = ""; }
private FTPSClient createClient() throws FileSystemException { final GenericFileName rootName = getRoot(); UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpsFileProvider.AUTHENTICATOR_TYPES); char[] userName = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())); char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())); return FtpsClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), userName, password, rootName.getPath(), getFileSystemOptions(), connectTimeout); } finally { UserAuthenticatorUtils.cleanup(authData); } }
private FTPSClient getFtpsClient() throws FileSystemException { if (ftpClient == null) { ftpClient = createClient(); FtpsDataChannelProtectionLevel level = FtpsFileSystemConfigBuilder.getInstance().getDataChannelProtectionLevel(fileSystemOptions); if (level != null) { try { ftpClient.execPBSZ(0); ftpClient.execPROT(level.name()); } catch (IOException e) { log.error(e.getMessage(),e); } } } return ftpClient; }
public void testStoreWithProtPAndReturnToProtCInActiveMode() throws Exception { ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE1.exists()); assertEquals(TEST_DATA.length, TEST_FILE1.length()); // needed due to bug in commons-net client.setServerSocketFactory(null); ((FTPSClient) client).execPROT("C"); client.storeFile(TEST_FILE2.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE2.exists()); assertEquals(TEST_DATA.length, TEST_FILE2.length()); }
public void testReceiveEmptyFile() throws Exception { client.enterLocalPassiveMode(); ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); File file = new File(ROOT_DIR, "foo"); file.createNewFile(); InputStream is = null; try { is = client.retrieveFileStream(file.getName()); assertEquals(-1, is.read(new byte[1024])); } finally { IoUtils.close(is); } }
private void secureClientDataConnection() throws NoSuchAlgorithmException, KeyManagementException { // FTPSClient does not support implicit data connections, so we hack it ourselves FTPSClient sclient = (FTPSClient) client; SSLContext context = SSLContext.getInstance("TLS"); // these are the same key and trust managers that we initialize the client with context.init(new KeyManager[] { clientKeyManager }, new TrustManager[] { clientTrustManager }, null); sclient.setSocketFactory(new FTPSSocketFactory(context)); SSLServerSocketFactory ssf = context.getServerSocketFactory(); sclient.setServerSocketFactory(ssf); // FTPClient should not use SSL secured sockets for the data connection }
@Override protected FTPSClient createFTPClient() throws Exception { FTPSClient client = new FTPSClient(useImplicit()); client.setNeedClientAuth(true); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); fis.close(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); kmf.init(ks, KEYSTORE_PASSWORD.toCharArray()); client.setKeyManager(kmf.getKeyManagers()[0]); return client; }
public FTPSNetworkClient(final String host, final int port, final String userName, final String password){ client = new FTPSClient(); this.host = host; this.port = port; this.username = userName; this.password = password; }
public static void connectToFTP(FTPSClient ftp, String ftpServer, int ftpPort) throws SocketException, IOException { ftp.connect(ftpServer, ftpPort); // After connection attempt, you should check the reply code to verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection, reply code: " + reply); } logger.debug("Connected to " + ftpServer + "."+ftp.getReplyString()); }
public void login(String host, String user, String pw, boolean secure) throws Exception { if(secure) client = new FTPSClient(true); else client = new FTPClient(); client.connect(host); boolean success = client.login(user, pw); if(!success) { throw new IOException("FTP login failed, host: "+host+", user: "+user); } client.setFileType(FTPClient.BINARY_FILE_TYPE); loginDir = client.printWorkingDirectory(); CTinfo.debugPrint("FTP login, u: "+user+", pw: "+pw+", loginDir: "+loginDir); }
@Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("ftpsClient", new FTPSClient("SSL")); jndi.bind("ftpsClientIn", new FTPSClient("SSL")); return jndi; }
@Override protected FTPClient ftpConnect() throws IOException { FilePathItem fpi = getFilePathItem(); FTPClient f = new FTPSClient(); f.connect(fpi.getHost()); f.login(fpi.getUsername(), fpi.getPassword()); return f; }
/** * Determines path on FTP server to domain root * * @param ftp * @param connectionInfo * @return "" if user user, or "/<DOMAIN>/" if user is SuperAdmin or has multi-domain access * @throws java.io.IOException */ private static String getPathToDomainRoot(FTPSClient ftp, SocrataConnectionInfo connectionInfo) throws IOException { String pathToDomainRoot = ""; System.out.println("Obtaining login role - ftp.listFiles(" + FTP_REQUEST_ID_FILENAME + ")"); FTPFile[] checkRequestIdFile = ftp.listFiles(FTP_REQUEST_ID_FILENAME); if(checkRequestIdFile.length == 0) { // user is a SuperAdmin or has multi-domain access String domainWithoutHTTP = connectionInfo.getUrl().replaceAll("https://", ""); domainWithoutHTTP = domainWithoutHTTP.replaceAll("/", ""); pathToDomainRoot = "/" + domainWithoutHTTP; } return pathToDomainRoot; }
/** * Sets (and returns) the FTP requestId to be a random 32 character hexidecimal value * * @param ftp authenticated ftps object * @param pathToRequestIdFile bsolute path on FTP server where requestId file is located * @return requestId that was set or if there was an error return error message in the * form 'FAILURE:...' * @throws java.io.IOException */ private static String setFTPRequestId(FTPSClient ftp, String pathToRequestIdFile) throws IOException { String requestId = Utils.generateRequestId(); InputStream inputRequestId = new ByteArrayInputStream(requestId.getBytes("UTF-8")); System.out.println("Setting job request ID - ftp.storeFile(" + pathToRequestIdFile + ", " + inputRequestId + ")"); if (!ftp.storeFile(pathToRequestIdFile, inputRequestId)) { return FAILURE_PREFIX + ": " + ftp.getReplyString(); } inputRequestId.close(); return requestId; }
/** * Records the DataSync version of this JAR/code (for tracking purposes). If setting the version * fails just print a message and do nothing else. * * @param ftp authenticated ftps object * @param pathToDataSyncVersionFile absolute path on FTP server where 'datasync-version' file is located */ private static void recordDataSyncVersion(FTPSClient ftp, String pathToDataSyncVersionFile) { try { String currentDataSyncVersion = VersionProvider.getThisVersion(); System.out.println("Recording DataSync version being used (" + currentDataSyncVersion + ")"); InputStream inputDataSyncVersion = new ByteArrayInputStream(currentDataSyncVersion.getBytes("UTF-8")); System.out.println("Setting job request ID - ftp.storeFile(" + pathToDataSyncVersionFile + ", " + inputDataSyncVersion + ")"); if (!ftp.storeFile(pathToDataSyncVersionFile, inputDataSyncVersion)) { System.out.println("Failed to record DataSync version: " + ftp.getReplyString() + " Continuing..."); } inputDataSyncVersion.close(); } catch (Exception e) { System.out.println("Failed to record DataSync version: " + e.getMessage() + ". Continuing..."); } }
/** * * Uploads the given input stream to the working directory of the given FTP object. * If transfer was successful (including no partial file transfers), move file to * the 'enqueue-job' directory. * * @param ftp authenticated ftps object * @param in input stream with contents to upload as a file * @param path absolute path on FTP server where file will be uploaded * @param filesize size (in bytes) the uploaded file should be (if filesize == 0, do * do not check filesize) * @return a string in the format of 'SUCCESS', if no errors or 'FAILURE: <error message>', * if there was an error during any step of the process */ private static String uploadAndEnqueue(FTPSClient ftp, InputStream in, final String path, long filesize) { try { if (!ftp.storeFile(path, in)) { return FAILURE_PREFIX + ": " + ftp.getReplyString(); } if(filesize != 0) { // verify the uploaded filesize == given filesize System.out.println("Verifying uploaded filesize of " + path + "..."); long uploadedFilesize = getFTPFilesize(ftp, path); if(filesize != uploadedFilesize) { return String.format(FAILURE_PREFIX + ": uploaded filesize (%d B) " + "did not match local filesize (%d B)", uploadedFilesize, filesize); } } // upload to enqueue directory File fileFromPath = new File(path); String datasetDirPath = fileFromPath.getParent(); System.out.println("Enqueing job - ftp.rename(" + path + ", " + datasetDirPath + "/" + FTP_ENQUEUE_JOB_DIRNAME + ")"); issueFtpCommandWithRetries(ftp, "rename", path, datasetDirPath + "/" + FTP_ENQUEUE_JOB_DIRNAME); } catch (IOException e) { e.printStackTrace(); return FAILURE_PREFIX + ": " + e.getMessage(); } return SUCCESS_PREFIX; }
public void testStoreWithProtPInPassiveMode() throws Exception { client.setRemoteVerificationEnabled(false); client.enterLocalPassiveMode(); ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE1.exists()); assertEquals(TEST_DATA.length, TEST_FILE1.length()); }
public void testStoreWithProtPInActiveMode() throws Exception { client.setRemoteVerificationEnabled(false); ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE1.exists()); assertEquals(TEST_DATA.length, TEST_FILE1.length()); }
public void testListEmptyDir() throws Exception { client.enterLocalPassiveMode(); ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); File dir = new File(ROOT_DIR, "dir"); dir.mkdir(); client.listFiles(dir.getName()); }
@Override protected FTPSClient createFTPClient() throws Exception { FTPSClient ftpsClient = new FTPSClient(useImplicit()); FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE); KeyStore store = KeyStore.getInstance("jks"); store.load(fin, KEYSTORE_PASSWORD.toCharArray()); fin.close(); // initialize key manager factory KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray()); // initialize trust manager factory TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(store); clientKeyManager = keyManagerFactory.getKeyManagers()[0]; clientTrustManager = trustManagerFactory.getTrustManagers()[0]; ftpsClient.setKeyManager(clientKeyManager); ftpsClient.setTrustManager(clientTrustManager); String auth = getAuthValue(); if (auth != null) { ftpsClient.setAuthValue(auth); if(auth.equals("SSL")) { // SSLv3 is disabled by default on the JBM JDK, therefore we need to enable it ftpsClient.setEnabledProtocols(new String[]{"SSLv3"}); } } return ftpsClient; }
public void testDisabled() throws Exception { ((FTPSClient) client) .setEnabledCipherSuites(new String[] { "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" }); try { doConnect(); fail("Must throw SSLHandshakeException"); } catch (SSLHandshakeException e) { // OK } }
public FTPClient getNewFTPSClient(Uri path, int mode) throws SocketException, IOException, AuthenticationException{ // Use default port if not set int port = path.getPort(); if (port<0) { port = 21; // default port } String username="anonymous"; // default user String password = ""; // default password NetworkCredentialsDatabase database = NetworkCredentialsDatabase.getInstance(); Credential cred = database.getCredential(path.toString()); if(cred!=null){ password= cred.getPassword(); username = cred.getUsername(); } FTPSClient ftp= new FTPSClient("TLS", false); //try to connect ftp.connect(path.getHost(), port); //login to server if(!ftp.login(username, password)) { ftp.logout(); throw new AuthenticationException(); } if(mode>=0){ ftp.setFileType(mode); } int reply = ftp.getReplyCode(); //FTPReply stores a set of constants for FTP reply codes. if (!FTPReply.isPositiveCompletion(reply)) { try { ftp.disconnect(); } catch (IOException e) { throw e; } return null; } //enter passive mode ftp.enterLocalPassiveMode(); // Set protection buffer size ftp.execPBSZ(0); // Set data channel protection to private ftp.execPROT("P"); return ftp; }
public FtpConnectionManager(boolean isSecured) { this.ftpClient = isSecured ? new FTPSClient() : new FTPClient(); isAvailableForTransfer = true; }
public static void loginToFTP(FTPSClient ftp, String ftpUser, String ftpPw) throws IOException { if (!ftp.login(ftpUser, ftpPw)) { throw new IOException("Unable to login!"); } }
/** * Returns the FTPSClient. This method exists only for convenient. */ public FTPSClient getFtpsClient() { return (FTPSClient) getFtpClient(); }
public FtpsOperations(FTPSClient client, FTPClientConfig clientConfig) { super(client, clientConfig); }
@Override protected FTPSClient getFtpClient() { return (FTPSClient) super.getFtpClient(); }
/** * Connect to a FTP server */ public void connect() throws IOException, SecurityException { if(this.isSecured()) { ftpClient = new FTPSClient(false); ((FTPSClient)ftpClient).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else ftpClient = new FTPClient(); // suppress login details ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter( new OutputStreamWriter(System.out,IO.CHARSET)), true)); int keepAliveTimeout = this.getKeepAliveTimeout(); if (keepAliveTimeout > 0) { ftpClient.setControlKeepAliveTimeout(keepAliveTimeout); } int controlKeepAliveReplyTimeout = this.getControlKeepAliveReplyTimeout(); if (controlKeepAliveReplyTimeout > 0) ftpClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); int port = this.getPort(); if(port > 0) ftpClient.connect(getHost(), getPort()); else ftpClient.connect(getHost()); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { disconnect(); return; } if (!ftpClient.login(this.getUsername(), new String(getPassword()))) throw new SecurityException("login failed"); if (isBinaryTransfer()) { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } else { ftpClient.setFileType(FTP.NON_PRINT_TEXT_FORMAT); ftpClient.setAutodetectUTF8(true); } if (isLocalActive()) ftpClient.enterLocalActiveMode(); else ftpClient.enterLocalPassiveMode(); ftpClient.setUseEPSVwithIPv4(isUseEpsvWithIPv4()); ftpClient.setCharset(this.getCharset()); this.connected = true; }
@Test public void newFtpsClientShouldCreateFTPSClientInstance() { assertThat(client.ftpClient, instanceOf(FTPSClient.class)); }
public FTPSFileSynchronizer(@NotNull FTPSConfiguration connectionInfo, @NotNull Project project, @NotNull ProgressIndicator indicator) { super(connectionInfo, project, indicator); this.ftps = new FTPSClient(connectionInfo.isRequireImplicitTLS()); this.getIndicator().setIndeterminate(true); }
public void testStoreWithProtPAndReturnToProtCInPassiveMode() throws Exception { client.setRemoteVerificationEnabled(false); client.enterLocalPassiveMode(); ((FTPSClient) client).execPROT("P"); assertTrue(getActiveSession().getDataConnection().isSecure()); client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE1.exists()); assertEquals(TEST_DATA.length, TEST_FILE1.length()); ((FTPSClient) client).execPROT("C"); assertFalse(getActiveSession().getDataConnection().isSecure()); client.storeFile(TEST_FILE2.getName(), new ByteArrayInputStream( TEST_DATA)); assertTrue(TEST_FILE2.exists()); assertEquals(TEST_DATA.length, TEST_FILE2.length()); }
@Override protected FTPSClient createFTPClient() throws Exception { return new FTPSClient(true); }
public void testEnabled() throws Exception { ((FTPSClient) client) .setEnabledCipherSuites(new String[] { "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA" }); connectClient(); }
public FtpsClient() { ftpClient = new FTPSClient(SSL, true); }
/** * Creates a new connection to the server. * @param hostname The host name. * @param port The port. * @param username The user name for authentication. * @param password The user's password. * @param workingDirectory The directory to use. * @param fileSystemOptions The FileSystemOptions. * @return The FTPSClient. * @throws FileSystemException if an error occurs. */ public static FTPSClient createConnection(String hostname, int port, char[] username, char[] password, String workingDirectory, FileSystemOptions fileSystemOptions) throws FileSystemException { return createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions, null); }