Search in sources :

Example 1 with FtpException

use of org.apache.ftpserver.ftplet.FtpException in project ddf by codice.

the class FtpRequestHandler method store.

private FtpletResult store(FtpSession session, FtpRequest request, boolean isStoreUnique) throws FtpException, IOException {
    LOGGER.debug("Beginning FTP ingest of {}", request.getArgument());
    Subject shiroSubject = (Subject) session.getAttribute(SUBJECT);
    if (shiroSubject == null) {
        return FtpletResult.DISCONNECT;
    }
    FtpFile ftpFile = null;
    String fileName = request.getArgument();
    try {
        ftpFile = session.getFileSystemView().getFile(fileName);
    } catch (FtpException e) {
        LOGGER.debug("Failed to retrieve file from FTP session");
    }
    String requestTypeString = isStoreUnique ? STOU_REQUEST : STOR_REQUEST;
    if (ftpFile == null) {
        LOGGER.debug("Sending FTP status code 501 to client - syntax errors in request parameters");
        session.write(new DefaultFtpReply(FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, requestTypeString));
        throw new FtpException("File to be transferred from client did not exist");
    }
    DataConnectionFactory connFactory = session.getDataConnection();
    if (connFactory instanceof IODataConnectionFactory) {
        InetAddress address = ((IODataConnectionFactory) connFactory).getInetAddress();
        if (address == null) {
            session.write(new DefaultFtpReply(FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS, "PORT or PASV must be issued first"));
            LOGGER.debug("Sending FTP status code 503 to client - PORT or PASV must be issued before STOR");
            throw new FtpException("FTP client address was null");
        }
    }
    if (!ftpFile.isWritable()) {
        session.write(new DefaultFtpReply(FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "Insufficient permissions"));
        LOGGER.debug("Sending FTP status code 550 to client - insufficient permissions to write file.");
        throw new FtpException("Insufficient permissions to write file");
    }
    session.write(new DefaultFtpReply(FtpReply.REPLY_150_FILE_STATUS_OKAY, requestTypeString + " " + fileName));
    LOGGER.debug("Replying to client with code 150 - file status okay");
    if (isDotFile(request.getArgument())) {
        DataConnection dataConnection;
        try {
            dataConnection = connFactory.openConnection();
        } catch (Exception e) {
            throw new IOException("Error getting the output stream from FTP session", e);
        }
        dataConnection.transferFromClient(session, addTempFileToSession(session, ftpFile.getAbsolutePath(), new TemporaryFileBackedOutputStream()));
        if (isStoreUnique) {
            session.write(new DefaultFtpReply(FtpReply.REPLY_125_DATA_CONNECTION_ALREADY_OPEN, "Storing data with unique name: " + fileName));
        }
        session.write(new DefaultFtpReply(FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "Closing data connection"));
        LOGGER.debug("Sending FTP status code 226 to client - closing data connection");
    } else {
        try (TemporaryFileBackedOutputStream outputStream = new TemporaryFileBackedOutputStream()) {
            DataConnection dataConnection = connFactory.openConnection();
            dataConnection.transferFromClient(session, outputStream);
            CreateStorageRequest createRequest = getCreateStorageRequest(fileName, outputStream);
            List<Metacard> storedMetacards = storeObject(shiroSubject, fileName, createRequest);
            if (isStoreUnique && !storedMetacards.isEmpty()) {
                String ids = storedMetacards.stream().map(Metacard::getId).collect(Collectors.joining(","));
                session.write(new DefaultFtpReply(FtpReply.REPLY_125_DATA_CONNECTION_ALREADY_OPEN, "Storing data with unique name: " + ids));
            }
            session.write(new DefaultFtpReply(FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "Closing data connection"));
            LOGGER.debug("Sending FTP status code 226 to client - closing data connection");
        } catch (FtpException fe) {
            throw new FtpException("Failure to create metacard for file " + fileName, fe);
        } catch (Exception e) {
            throw new IOException("Error getting the output stream from FTP session", e);
        } finally {
            session.getDataConnection().closeDataConnection();
        }
    }
    return FtpletResult.SKIP;
}
Also used : DataConnection(org.apache.ftpserver.ftplet.DataConnection) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) IODataConnectionFactory(org.apache.ftpserver.impl.IODataConnectionFactory) IOException(java.io.IOException) FtpFile(org.apache.ftpserver.ftplet.FtpFile) Subject(ddf.security.Subject) DefaultFtpReply(org.apache.ftpserver.ftplet.DefaultFtpReply) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) FtpException(org.apache.ftpserver.ftplet.FtpException) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) MimeTypeResolutionException(ddf.mime.MimeTypeResolutionException) DataConnectionFactory(org.apache.ftpserver.ftplet.DataConnectionFactory) IODataConnectionFactory(org.apache.ftpserver.impl.IODataConnectionFactory) Metacard(ddf.catalog.data.Metacard) FtpException(org.apache.ftpserver.ftplet.FtpException) InetAddress(java.net.InetAddress) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest)

Example 2 with FtpException

use of org.apache.ftpserver.ftplet.FtpException in project alliance by codice.

the class MockNsili method startFtpWebServer.

public void startFtpWebServer(int port) {
    FtpServerFactory ftpServerFactory = new FtpServerFactory();
    ListenerFactory listenerFactory = new ListenerFactory();
    listenerFactory.setPort(port);
    ftpServerFactory.addListener("default", listenerFactory.createListener());
    PropertiesUserManagerFactory propertiesUserManagerFactory = new PropertiesUserManagerFactory();
    UserManager userManager = propertiesUserManagerFactory.createUserManager();
    BaseUser baseUser = new BaseUser();
    baseUser.setName(MOCK_SERVER_USERNAME);
    baseUser.setPassword(MOCK_SERVER_PASSWORD);
    try {
        ftpHomeDirectoryPath = Files.createTempDirectory("home_");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> FileUtils.deleteQuietly(ftpHomeDirectoryPath.toFile())));
        baseUser.setHomeDirectory(ftpHomeDirectoryPath.toString());
    } catch (IOException e) {
        LOGGER.info("Unable to set ftp endpoint to a temporary home directory.");
    }
    try {
        userManager.save(baseUser);
        ftpServerFactory.setUserManager(userManager);
        FtpServer ftpServer = ftpServerFactory.createServer();
        ftpServer.start();
    } catch (FtpException e) {
        LOGGER.error("Unable to start FTP server.", e);
    }
    LOGGER.info("Setting the ftp server's publish address to be ftp://localhost:{}/", port);
}
Also used : BaseUser(org.apache.ftpserver.usermanager.impl.BaseUser) FtpServerFactory(org.apache.ftpserver.FtpServerFactory) UserManager(org.apache.ftpserver.ftplet.UserManager) PropertiesUserManagerFactory(org.apache.ftpserver.usermanager.PropertiesUserManagerFactory) FtpServer(org.apache.ftpserver.FtpServer) FtpException(org.apache.ftpserver.ftplet.FtpException) IOException(java.io.IOException) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory)

Example 3 with FtpException

use of org.apache.ftpserver.ftplet.FtpException in project lobcder by skoulouzis.

the class MiltonFsView method changeWorkingDirectory.

@Override
public boolean changeWorkingDirectory(String dir) throws FtpException {
    try {
        log.debug("cd: " + dir + " from " + currentPath);
        Path p = Path.path(dir);
        ResourceAndPath rp = getResource(p);
        if (rp.resource == null) {
            log.debug("not found: " + p);
            return false;
        } else if (rp.resource instanceof CollectionResource) {
            current = (CollectionResource) rp.resource;
            currentPath = rp.path;
            log.debug("currentPath is now: " + currentPath);
            return true;
        } else {
            log.debug("not a collection: " + rp.resource.getName());
            return false;
        }
    } catch (NotAuthorizedException ex) {
        throw new FtpException(ex);
    } catch (BadRequestException ex) {
        throw new FtpException(ex);
    }
}
Also used : Path(io.milton.common.Path) CollectionResource(io.milton.resource.CollectionResource) BadRequestException(io.milton.http.exceptions.BadRequestException) FtpException(org.apache.ftpserver.ftplet.FtpException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 4 with FtpException

use of org.apache.ftpserver.ftplet.FtpException in project lobcder by skoulouzis.

the class MiltonFsView method getFile.

@Override
public FtpFile getFile(String path) throws FtpException {
    try {
        log.debug("getFile: " + path);
        if (path.startsWith(".")) {
            path = currentPath.toString() + path.substring(1);
            log.debug("getFile2: " + path);
        }
        Path p = Path.path(path);
        ResourceAndPath rp = getResource(p);
        if (rp.resource == null) {
            log.debug("returning new file");
            return new MiltonFtpFile(this, rp.path, this.current, null, user);
        } else {
            return new MiltonFtpFile(this, rp.path, rp.resource, user);
        }
    } catch (NotAuthorizedException ex) {
        throw new FtpException(ex);
    } catch (BadRequestException ex) {
        throw new FtpException(ex);
    }
}
Also used : Path(io.milton.common.Path) BadRequestException(io.milton.http.exceptions.BadRequestException) FtpException(org.apache.ftpserver.ftplet.FtpException) NotAuthorizedException(io.milton.http.exceptions.NotAuthorizedException)

Example 5 with FtpException

use of org.apache.ftpserver.ftplet.FtpException in project AmazeFileManager by TeamAmaze.

the class FTPService method run.

@Override
public void run() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    FtpServerFactory serverFactory = new FtpServerFactory();
    ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
    connectionConfigFactory.setAnonymousLoginEnabled(true);
    serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
    String usernamePreference = preferences.getString(KEY_PREFERENCE_USERNAME, DEFAULT_USERNAME);
    if (!usernamePreference.equals(DEFAULT_USERNAME)) {
        username = usernamePreference;
        try {
            password = CryptUtil.decryptPassword(getApplicationContext(), preferences.getString(KEY_PREFERENCE_PASSWORD, ""));
            isPasswordProtected = true;
        } catch (GeneralSecurityException | IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
            // can't decrypt the password saved in preferences, remove the preference altogether
            // and start an anonymous connection instead
            preferences.edit().putString(FTPService.KEY_PREFERENCE_PASSWORD, "").apply();
            isPasswordProtected = false;
        }
    }
    BaseUser user = new BaseUser();
    if (!isPasswordProtected) {
        user.setName("anonymous");
    } else {
        user.setName(username);
        user.setPassword(password);
    }
    user.setHomeDirectory(preferences.getString(KEY_PREFERENCE_PATH, DEFAULT_PATH));
    List<Authority> list = new ArrayList<>();
    list.add(new WritePermission());
    user.setAuthorities(list);
    try {
        serverFactory.getUserManager().save(user);
    } catch (FtpException e) {
        e.printStackTrace();
    }
    ListenerFactory fac = new ListenerFactory();
    if (preferences.getBoolean(KEY_PREFERENCE_SECURE, DEFAULT_SECURE)) {
        SslConfigurationFactory sslConfigurationFactory = new SslConfigurationFactory();
        File file;
        try {
            InputStream stream = getResources().openRawResource(R.raw.key);
            file = File.createTempFile("keystore.bks", "");
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(stream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            file = null;
        }
        if (file != null) {
            sslConfigurationFactory.setKeystoreFile(file);
            sslConfigurationFactory.setKeystorePassword("vishal007");
            fac.setSslConfiguration(sslConfigurationFactory.createSslConfiguration());
            fac.setImplicitSsl(true);
        } else {
            // no keystore found
            preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply();
        }
    }
    fac.setPort(getPort(preferences));
    fac.setIdleTimeout(preferences.getInt(KEY_PREFERENCE_TIMEOUT, DEFAULT_TIMEOUT));
    serverFactory.addListener("default", fac.createListener());
    try {
        server = serverFactory.createServer();
        server.start();
        sendBroadcast(new Intent(FTPService.ACTION_STARTED).putExtra(TAG_STARTED_BY_TILE, isStartedByTile));
    } catch (Exception e) {
        sendBroadcast(new Intent(FTPService.ACTION_FAILEDTOSTART));
    }
}
Also used : BaseUser(org.apache.ftpserver.usermanager.impl.BaseUser) SharedPreferences(android.content.SharedPreferences) Authority(org.apache.ftpserver.ftplet.Authority) FtpServerFactory(org.apache.ftpserver.FtpServerFactory) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) ConnectionConfigFactory(org.apache.ftpserver.ConnectionConfigFactory) IOException(java.io.IOException) WritePermission(org.apache.ftpserver.usermanager.impl.WritePermission) SocketException(java.net.SocketException) GeneralSecurityException(java.security.GeneralSecurityException) FtpException(org.apache.ftpserver.ftplet.FtpException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileOutputStream(java.io.FileOutputStream) FtpException(org.apache.ftpserver.ftplet.FtpException) SslConfigurationFactory(org.apache.ftpserver.ssl.SslConfigurationFactory) File(java.io.File) ListenerFactory(org.apache.ftpserver.listener.ListenerFactory)

Aggregations

FtpException (org.apache.ftpserver.ftplet.FtpException)7 BadRequestException (io.milton.http.exceptions.BadRequestException)3 NotAuthorizedException (io.milton.http.exceptions.NotAuthorizedException)3 IOException (java.io.IOException)3 FtpServerFactory (org.apache.ftpserver.FtpServerFactory)3 ListenerFactory (org.apache.ftpserver.listener.ListenerFactory)3 BaseUser (org.apache.ftpserver.usermanager.impl.BaseUser)3 Path (io.milton.common.Path)2 CollectionResource (io.milton.resource.CollectionResource)2 ArrayList (java.util.ArrayList)2 ConnectionConfigFactory (org.apache.ftpserver.ConnectionConfigFactory)2 Authority (org.apache.ftpserver.ftplet.Authority)2 WritePermission (org.apache.ftpserver.usermanager.impl.WritePermission)2 PendingIntent (android.app.PendingIntent)1 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 CreateStorageRequest (ddf.catalog.content.operation.CreateStorageRequest)1 Metacard (ddf.catalog.data.Metacard)1 IngestException (ddf.catalog.source.IngestException)1 SourceUnavailableException (ddf.catalog.source.SourceUnavailableException)1