code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Type safe enum for describing the data type
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public enum DataType {
/**
* Binary data type
*/
BINARY,
/**
* ASCII data type
*/
ASCII;
/**
* Parses the argument value from the TYPE command into the type safe class
*
* @param argument
* The argument value from the TYPE command. Not case sensitive
* @return The appropriate data type
* @throws IllegalArgumentException
* If the data type is unknown
*/
public static DataType parseArgument(char argument) {
switch (argument) {
case 'A':
case 'a':
return ASCII;
case 'I':
case 'i':
return BINARY;
default:
throw new IllegalArgumentException("Unknown data type: " + argument);
}
}
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/DataType.java | Java | art | 1,762 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Factory for file system implementations - it returns the file system view for user.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileSystemFactory {
/**
* Create user specific file system view.
* @param user The user for which the file system should be created
* @return The current {@link FileSystemView} for the provided user
* @throws FtpException
*/
FileSystemView createFileSystemView(User user) throws FtpException;
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FileSystemFactory.java | Java | art | 1,360 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* One FtpRequest made by the client.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpRequest {
/**
* Get the client request string.
* @return The full request line, e.g. "MKDIR newdir"
*/
String getRequestLine();
/**
* Returns the ftp request command.
* @return The command part of the request line, e.g. "MKDIR"
*/
String getCommand();
/**
* Get the ftp request argument.
* @return The argument part of the request line, e.g. "newdir"
*/
String getArgument();
/**
* Check if request contains an argument
*
* @return true if an argument is available
*/
boolean hasArgument();
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/FtpRequest.java | Java | art | 1,578 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface DataConnectionFactory {
/**
* Open an active data connection
*
* @return The open data connection
* @throws Exception
*/
DataConnection openConnection() throws Exception;
/**
* Indicates whether the data socket created by this factory will be secure
* that is, running over SSL/TLS.
*
* @return true if the data socket will be secured
*/
boolean isSecure();
/**
* Close data socket. If no open data connection exists,
* this will silently ignore the call.
*/
void closeDataConnection();
} | zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/DataConnectionFactory.java | Java | art | 1,526 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* Type safe enum for describing the structure
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public enum Structure {
/**
* File structure
*/
FILE;
/**
* Parses the argument value from the STRU command into the type safe class
*
* @param argument
* The argument value from the STRU command. Not case sensitive
* @return The appropriate structure
* @throws IllegalArgumentException
* If the structure is unknown
*/
public static Structure parseArgument(char argument) {
switch (argument) {
case 'F':
case 'f':
return FILE;
default:
throw new IllegalArgumentException("Unknown structure: " + argument);
}
}
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/Structure.java | Java | art | 1,646 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* User manager interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface UserManager {
/**
* Get user by name.
*
* @param username the name to search for.
* @throws FtpException when the UserManager can't fulfill the request.
* @return the user with the specified name, or null if a such user does
* not exist.
*/
User getUserByName(String username) throws FtpException;
/**
* Get all user names in the system.
*
* @throws FtpException when the UserManager can't fulfill the request.
* @return an array of username strings, note that the result should never
* be null, if there is no users the result is an empty array.
*/
String[] getAllUserNames() throws FtpException;
/**
* Delete the user from the system.
* @param username The name of the {@link User} to delete
*
* @throws FtpException when the UserManager can't fulfill the request.
* @throws UnsupportedOperationException
* if UserManager in read-only mode
*/
void delete(String username) throws FtpException;
/**
* Save user. If a new user, create it else update the existing user.
*
* @param user the Uset to save
* @throws FtpException when the UserManager can't fulfill the request.
* @throws UnsupportedOperationException
* if UserManager in read-only mode
*/
void save(User user) throws FtpException;
/**
* Check if the user exists.
* @param username the name of the user to check.
* @return true if the user exist, false otherwise.
* @throws FtpException
*/
boolean doesExist(String username) throws FtpException;
/**
* Authenticate user
* @param authentication The {@link Authentication} that proves the users identity
* @return the authenticated account.
* @throws AuthenticationFailedException
* @throws FtpException when the UserManager can't fulfill the request.
*/
User authenticate(Authentication authentication)
throws AuthenticationFailedException;
/**
* Get admin user name
* @return the admin user name
* @throws FtpException when the UserManager can't fulfill the request.
*/
String getAdminName() throws FtpException;
/**
* Check if the user is admin.
* @param username The name of the {@link User} to check
* @return true if user with this login is administrator
* @throws FtpException when the UserManager can't fulfill the request.
*/
boolean isAdmin(String username) throws FtpException;
}
| zzh-simple-hr | Zftp/ftplet/main/org/apache/ftpserver/ftplet/UserManager.java | Java | art | 3,529 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftplet;
import java.io.IOException;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ExampleFtplet extends DefaultFtplet {
@Override
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
session.write(new DefaultFtpReply(550, "Error!"));
return FtpletResult.SKIP;
}
@Override
public FtpletResult onMkdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
if (session.isSecure() && session.getDataConnection().isSecure()) {
// all is good
}
return null;
}
}
| zzh-simple-hr | Zftp/ftplet/test/org/apache/ftpserver/ftplet/ExampleFtplet.java | Java | art | 1,523 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>NIO based listener</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/package.html | HTML | art | 969 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.ftpserver.listener.nio;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.DefaultFtpRequest;
import org.apache.ftpserver.impl.FtpHandler;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.MdcInjectionFilter;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Adapter between MINA handler and the {@link FtpHandler} interface
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class FtpHandlerAdapter implements IoHandler {
private FtpServerContext context;
private FtpHandler ftpHandler;
public FtpHandlerAdapter(FtpServerContext context, FtpHandler ftpHandler) {
this.context = context;
this.ftpHandler = ftpHandler;
}
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
ftpHandler.exceptionCaught(ftpSession, cause);
}
public void messageReceived(IoSession session, Object message)
throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
FtpRequest request = new DefaultFtpRequest(message.toString());
ftpHandler.messageReceived(ftpSession, request);
}
public void messageSent(IoSession session, Object message) throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
ftpHandler.messageSent(ftpSession, (FtpReply) message);
}
public void sessionClosed(IoSession session) throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
ftpHandler.sessionClosed(ftpSession);
}
public void sessionCreated(IoSession session) throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
MdcInjectionFilter.setProperty(session, "session", ftpSession.getSessionId().toString());
ftpHandler.sessionCreated(ftpSession);
}
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
ftpHandler.sessionIdle(ftpSession, status);
}
public void sessionOpened(IoSession session) throws Exception {
FtpIoSession ftpSession = new FtpIoSession(session, context);
ftpHandler.sessionOpened(ftpSession);
}
public FtpHandler getFtpHandler() {
return ftpHandler;
}
public void setFtpHandler(FtpHandler handler) {
this.ftpHandler = handler;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/FtpHandlerAdapter.java | Java | art | 3,700 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.ftpserver.listener.nio;
import java.nio.charset.Charset;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.textline.TextLineDecoder;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Factory for creating decoders and encoders
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpServerProtocolCodecFactory implements ProtocolCodecFactory {
private ProtocolDecoder decoder = new TextLineDecoder(Charset
.forName("UTF-8"));
private ProtocolEncoder encoder = new FtpResponseEncoder();
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
}
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/FtpServerProtocolCodecFactory.java | Java | art | 1,826 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.listener.nio;
import java.net.InetAddress;
import java.util.List;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.ipfilter.DefaultIpFilter;
import org.apache.ftpserver.ipfilter.IpFilter;
import org.apache.ftpserver.ipfilter.IpFilterType;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.filter.firewall.Subnet;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Common base class for listener implementations
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public abstract class AbstractListener implements Listener {
private String serverAddress;
private int port = 21;
private SslConfiguration ssl;
private boolean implicitSsl = false;
private int idleTimeout;
private List<InetAddress> blockedAddresses;
private List<Subnet> blockedSubnets;
private IpFilter ipFilter = null;
private DataConnectionConfiguration dataConnectionConfig;
/**
* @deprecated Use the constructor with IpFilter instead.
* Constructor for internal use, do not use directly. Instead use {@link ListenerFactory}
*/
@Deprecated
public AbstractListener(String serverAddress, int port, boolean implicitSsl,
SslConfiguration sslConfiguration, DataConnectionConfiguration dataConnectionConfig,
int idleTimeout, List<InetAddress> blockedAddresses, List<Subnet> blockedSubnets) {
this(serverAddress, port, implicitSsl, sslConfiguration,
dataConnectionConfig, idleTimeout, createBlackListFilter(blockedAddresses, blockedSubnets));
this.blockedAddresses = blockedAddresses;
this.blockedSubnets = blockedSubnets;
}
/**
* Constructor for internal use, do not use directly. Instead use {@link ListenerFactory}
*/
public AbstractListener(String serverAddress, int port, boolean implicitSsl,
SslConfiguration sslConfiguration, DataConnectionConfiguration dataConnectionConfig,
int idleTimeout, IpFilter ipFilter) {
this.serverAddress = serverAddress;
this.port = port;
this.implicitSsl = implicitSsl;
this.dataConnectionConfig = dataConnectionConfig;
this.ssl = sslConfiguration;
this.idleTimeout = idleTimeout;
this.ipFilter = ipFilter;
}
/**
* Creates an IpFilter that blacklists the given IP addresses and/or Subnets.
* @param blockedAddresses the addresses to block
* @param blockedSubnets the subnets to block
* @return an IpFilter that blacklists the given IP addresses and/or Subnets.
*/
private static IpFilter createBlackListFilter(List<InetAddress> blockedAddresses,
List<Subnet> blockedSubnets) {
if(blockedAddresses == null && blockedSubnets == null) {
return null;
}
//Initialize the IP filter with Deny type
DefaultIpFilter ipFilter = new DefaultIpFilter(IpFilterType.DENY);
if(blockedSubnets != null) {
ipFilter.addAll(blockedSubnets);
}
if(blockedAddresses != null) {
for(InetAddress address:blockedAddresses) {
ipFilter.add(new Subnet(address, 32));
}
}
return ipFilter;
}
/**
* {@inheritDoc}
*/
public boolean isImplicitSsl() {
return implicitSsl;
}
/**
* {@inheritDoc}
*/
public int getPort() {
return port;
}
/**
* Used internally to update the port after binding
* @param port
*/
protected void setPort(int port) {
this.port = port;
}
/**
* {@inheritDoc}
*/
public String getServerAddress() {
return serverAddress;
}
/**
* {@inheritDoc}
*/
public SslConfiguration getSslConfiguration() {
return ssl;
}
/**
* {@inheritDoc}
*/
public DataConnectionConfiguration getDataConnectionConfiguration() {
return dataConnectionConfig;
}
/**
* Get the number of seconds during which no network activity
* is allowed before a session is closed due to inactivity.
* @return The idle time out
*/
public int getIdleTimeout() {
return idleTimeout;
}
/**
* Retrives the {@link InetAddress} for which this listener blocks
* connections
*
* @return The list of {@link InetAddress}es
*/
public List<InetAddress> getBlockedAddresses() {
return blockedAddresses;
}
/**
* Retrieves the {@link Subnet}s for this listener blocks connections
*
* @return The list of {@link Subnet}s
*/
public List<Subnet> getBlockedSubnets() {
return blockedSubnets;
}
public IpFilter getIpFilter() {
return ipFilter;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/AbstractListener.java | Java | art | 5,692 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.listener.nio;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.LoggingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Specialized @see {@link LoggingFilter} that optionally masks FTP passwords.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpLoggingFilter extends LoggingFilter {
private boolean maskPassword = true;
private final Logger logger;
/**
* @see LoggingFilter#LoggingFilter()
*/
public FtpLoggingFilter() {
this(FtpLoggingFilter.class.getName());
}
/**
* @see LoggingFilter#LoggingFilter(Class)
*/
public FtpLoggingFilter(Class<?> clazz) {
this(clazz.getName());
}
/**
* @see LoggingFilter#LoggingFilter(String)
*/
public FtpLoggingFilter(String name) {
super(name);
logger = LoggerFactory.getLogger(name);
}
/**
* @see LoggingFilter#messageReceived(org.apache.mina.core.IoFilter.NextFilter,
* IoSession, Object)
*/
@Override
public void messageReceived(NextFilter nextFilter, IoSession session,
Object message) throws Exception {
String request = (String) message;
String logMessage;
if (maskPassword) {
if (request.trim().toUpperCase().startsWith("PASS ")) {
logMessage = "PASS *****";
} else {
logMessage = request;
}
} else {
logMessage = request;
}
logger.info("RECEIVED: {}", logMessage);
nextFilter.messageReceived(session, message);
}
/**
* Are password masked?
*
* @return true if passwords are masked
*/
public boolean isMaskPassword() {
return maskPassword;
}
/**
* Mask password in log messages
*
* @param maskPassword
* true if passwords should be masked
*/
public void setMaskPassword(boolean maskPassword) {
this.maskPassword = maskPassword;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/FtpLoggingFilter.java | Java | art | 2,988 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.listener.nio;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.impl.DefaultFtpHandler;
import org.apache.ftpserver.impl.FtpHandler;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.ipfilter.IpFilter;
import org.apache.ftpserver.ipfilter.MinaIpFilter;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.ClientAuth;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import org.apache.mina.filter.firewall.Subnet;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The default {@link Listener} implementation.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NioListener extends AbstractListener {
private final Logger LOG = LoggerFactory.getLogger(NioListener.class);
private SocketAcceptor acceptor;
private InetSocketAddress address;
boolean suspended = false;
private FtpHandler handler = new DefaultFtpHandler();
private FtpServerContext context;
/**
* @deprecated Use the constructor with IpFilter instead.
* Constructor for internal use, do not use directly. Instead use {@link ListenerFactory}
*/
@Deprecated
public NioListener(String serverAddress, int port,
boolean implicitSsl,
SslConfiguration sslConfiguration,
DataConnectionConfiguration dataConnectionConfig,
int idleTimeout, List<InetAddress> blockedAddresses, List<Subnet> blockedSubnets) {
super(serverAddress, port, implicitSsl, sslConfiguration, dataConnectionConfig,
idleTimeout, blockedAddresses, blockedSubnets);
}
/**
* Constructor for internal use, do not use directly. Instead use {@link ListenerFactory}
*/
public NioListener(String serverAddress, int port,
boolean implicitSsl,
SslConfiguration sslConfiguration,
DataConnectionConfiguration dataConnectionConfig,
int idleTimeout, IpFilter ipFilter) {
super(serverAddress, port, implicitSsl, sslConfiguration, dataConnectionConfig,
idleTimeout, ipFilter);
}
/**
* @see Listener#start(FtpServerContext)
*/
public synchronized void start(FtpServerContext context) {
if(!isStopped()) {
// listener already started, don't allow
throw new IllegalStateException("Listener already started");
}
try {
this.context = context;
acceptor = new NioSocketAcceptor(Runtime.getRuntime()
.availableProcessors());
if (getServerAddress() != null) {
address = new InetSocketAddress(getServerAddress(), getPort());
} else {
address = new InetSocketAddress(getPort());
}
acceptor.setReuseAddress(true);
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,
getIdleTimeout());
// Decrease the default receiver buffer size
((SocketSessionConfig) acceptor.getSessionConfig())
.setReceiveBufferSize(512);
MdcInjectionFilter mdcFilter = new MdcInjectionFilter();
acceptor.getFilterChain().addLast("mdcFilter", mdcFilter);
IpFilter ipFilter = getIpFilter();
if(ipFilter != null) {
// add and IP filter to the filter chain.
acceptor.getFilterChain().addLast("ipFilter", new MinaIpFilter(ipFilter));
}
acceptor.getFilterChain().addLast("threadPool",
new ExecutorFilter(context.getThreadPoolExecutor()));
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new FtpServerProtocolCodecFactory()));
acceptor.getFilterChain().addLast("mdcFilter2", mdcFilter);
acceptor.getFilterChain().addLast("logger", new FtpLoggingFilter());
if (isImplicitSsl()) {
SslConfiguration ssl = getSslConfiguration();
SslFilter sslFilter;
try {
sslFilter = new SslFilter(ssl.getSSLContext());
} catch (GeneralSecurityException e) {
throw new FtpServerConfigurationException("SSL could not be initialized, check configuration");
}
if (ssl.getClientAuth() == ClientAuth.NEED) {
sslFilter.setNeedClientAuth(true);
} else if (ssl.getClientAuth() == ClientAuth.WANT) {
sslFilter.setWantClientAuth(true);
}
if (ssl.getEnabledCipherSuites() != null) {
sslFilter.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
}
acceptor.getFilterChain().addFirst("sslFilter", sslFilter);
}
handler.init(context, this);
acceptor.setHandler(new FtpHandlerAdapter(context, handler));
try {
acceptor.bind(address);
} catch (IOException e) {
throw new FtpServerConfigurationException("Failed to bind to address " + address + ", check configuration", e);
}
updatePort();
} catch(RuntimeException e) {
// clean up if we fail to start
stop();
throw e;
}
}
private void updatePort() {
// update the port to the real port bound by the listener
setPort(acceptor.getLocalAddress().getPort());
}
/**
* @see Listener#stop()
*/
public synchronized void stop() {
// close server socket
if (acceptor != null) {
acceptor.unbind();
acceptor.dispose();
acceptor = null;
}
context = null;
}
/**
* @see Listener#isStopped()
*/
public boolean isStopped() {
return acceptor == null;
}
/**
* @see Listener#isSuspended()
*/
public boolean isSuspended() {
return suspended;
}
/**
* @see Listener#resume()
*/
public synchronized void resume() {
if (acceptor != null && suspended) {
try {
LOG.debug("Resuming listener");
acceptor.bind(address);
LOG.debug("Listener resumed");
updatePort();
suspended = false;
} catch (IOException e) {
LOG.error("Failed to resume listener", e);
}
}
}
/**
* @see Listener#suspend()
*/
public synchronized void suspend() {
if (acceptor != null && !suspended) {
LOG.debug("Suspending listener");
acceptor.unbind();
suspended = true;
LOG.debug("Listener suspended");
}
}
/**
* @see Listener#getActiveSessions()
*/
public synchronized Set<FtpIoSession> getActiveSessions() {
Map<Long, IoSession> sessions = acceptor.getManagedSessions();
Set<FtpIoSession> ftpSessions = new HashSet<FtpIoSession>();
for (IoSession session : sessions.values()) {
ftpSessions.add(new FtpIoSession(session, context));
}
return ftpSessions;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/NioListener.java | Java | art | 9,471 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.ftpserver.listener.nio;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
/**
* <strong>Internal class, do not use directly.</strong>
*
* A {@link MessageEncoder} that encodes {@link FtpReply}.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpResponseEncoder extends ProtocolEncoderAdapter {
private static final CharsetEncoder ENCODER = Charset.forName("UTF-8")
.newEncoder();
public void encode(IoSession session, Object message,
ProtocolEncoderOutput out) throws Exception {
String value = message.toString();
IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true);
buf.putString(value, ENCODER);
buf.flip();
out.write(buf);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/nio/FtpResponseEncoder.java | Java | art | 1,963 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.listener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ipfilter.IpFilter;
import org.apache.ftpserver.listener.nio.NioListener;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.filter.firewall.Subnet;
/**
* Factory for listeners. Listeners themselves are immutable and must be
* created using this factory.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ListenerFactory {
private String serverAddress;
private int port = 21;
private SslConfiguration ssl;
private boolean implicitSsl = false;
private DataConnectionConfiguration dataConnectionConfig = new DataConnectionConfigurationFactory()
.createDataConnectionConfiguration();
private int idleTimeout = 300;
private List<InetAddress> blockedAddresses;
private List<Subnet> blockedSubnets;
/**
* The IP filter
*/
private IpFilter ipFilter = null;
/**
* Default constructor
*/
public ListenerFactory() {
// do nothing
}
/**
* Copy constructor, will copy properties from the provided listener.
* @param listener The listener which properties will be used for this factory
*/
public ListenerFactory(Listener listener) {
serverAddress = listener.getServerAddress();
port = listener.getPort();
ssl = listener.getSslConfiguration();
implicitSsl = listener.isImplicitSsl();
dataConnectionConfig = listener.getDataConnectionConfiguration();
idleTimeout = listener.getIdleTimeout();
//TODO remove the next two lines if and when we remove the deprecated methods.
blockedAddresses = listener.getBlockedAddresses();
blockedSubnets = listener.getBlockedSubnets();
this.ipFilter = listener.getIpFilter();
}
/**
* Create a listener based on the settings of this factory. The listener is immutable.
* @return The created listener
*/
public Listener createListener() {
try{
InetAddress.getByName(serverAddress);
}catch(UnknownHostException e){
throw new FtpServerConfigurationException("Unknown host",e);
}
//Deal with the old style black list and new IP Filter here.
if(ipFilter != null) {
if(blockedAddresses != null || blockedSubnets != null) {
throw new IllegalStateException("Usage of IPFilter in combination with blockedAddesses/subnets is not supported. ");
}
}
if(blockedAddresses != null || blockedSubnets != null) {
return new NioListener(serverAddress, port, implicitSsl, ssl,
dataConnectionConfig, idleTimeout, blockedAddresses, blockedSubnets);
}
else {
return new NioListener(serverAddress, port, implicitSsl, ssl,
dataConnectionConfig, idleTimeout, ipFilter);
}
}
/**
* Is listeners created by this factory in SSL mode automatically or must the client explicitly
* request to use SSL
*
* @return true is listeners created by this factory is automatically in SSL mode, false
* otherwise
*/
public boolean isImplicitSsl() {
return implicitSsl;
}
/**
* Should listeners created by this factory be in SSL mode automatically or must the client
* explicitly request to use SSL
*
* @param implicitSsl
* true is listeners created by this factory should automatically be in SSL mode,
* false otherwise
*/
public void setImplicitSsl(boolean implicitSsl) {
this.implicitSsl = implicitSsl;
}
/**
* Get the port on which listeners created by this factory is waiting for requests.
*
* @return The port
*/
public int getPort() {
return port;
}
/**
* Set the port on which listeners created by this factory will accept requests. Or set to 0
* (zero) is the port should be automatically assigned
*
* @param port
* The port to use.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Get the {@link InetAddress} used for binding the local socket. Defaults
* to null, that is, the server binds to all available network interfaces
*
* @return The local socket {@link InetAddress}, if set
*/
public String getServerAddress() {
return serverAddress;
}
/**
* Set the {@link InetAddress} used for binding the local socket. Defaults
* to null, that is, the server binds to all available network interfaces
*
* @param serverAddress
* The local socket {@link InetAddress}
*/
public void setServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
}
/**
* Get the {@link SslConfiguration} used for listeners created by this factory
*
* @return The {@link SslConfiguration}
*/
public SslConfiguration getSslConfiguration() {
return ssl;
}
/**
* Set the {@link SslConfiguration} to use by listeners created by this factory
* @param ssl The {@link SslConfiguration}
*/
public void setSslConfiguration(SslConfiguration ssl) {
this.ssl = ssl;
}
/**
* Get configuration for data connections made within listeners created by this factory
*
* @return The data connection configuration
*/
public DataConnectionConfiguration getDataConnectionConfiguration() {
return dataConnectionConfig;
}
/**
* Set configuration for data connections made within listeners created by this factory
*
* @param dataConnectionConfig
* The data connection configuration
*/
public void setDataConnectionConfiguration(
DataConnectionConfiguration dataConnectionConfig) {
this.dataConnectionConfig = dataConnectionConfig;
}
/**
* Get the number of seconds during which no network activity
* is allowed before a session is closed due to inactivity.
* @return The idle time out
*/
public int getIdleTimeout() {
return idleTimeout;
}
/**
* Set the number of seconds during which no network activity
* is allowed before a session is closed due to inactivity.
*
* @param idleTimeout The idle timeout in seconds
*/
public void setIdleTimeout(int idleTimeout) {
this.idleTimeout = idleTimeout;
}
/**
* @deprecated Replaced by the IpFilter.
* Retrieves the {@link InetAddress} for which listeners created by this factory blocks
* connections
*
* @return The list of {@link InetAddress}es
*/
@Deprecated
public List<InetAddress> getBlockedAddresses() {
return blockedAddresses;
}
/**
* @deprecated Replaced by the IpFilter.
* Sets the {@link InetAddress} that listeners created by this factory will block from
* connecting
*
* @param blockedAddresses
* The list of {@link InetAddress}es
*/
@Deprecated
public void setBlockedAddresses(List<InetAddress> blockedAddresses) {
this.blockedAddresses = blockedAddresses;
}
/**
* @deprecated Replaced by the IpFilter.
* Retrives the {@link Subnet}s for which listeners created by this factory blocks connections
*
* @return The list of {@link Subnet}s
*/
@Deprecated
public List<Subnet> getBlockedSubnets() {
return blockedSubnets;
}
/**
* @deprecated Replaced by the IpFilter.
* Sets the {@link Subnet}s that listeners created by this factory will block from connecting
* @param blockedSubnets
* The list of {@link Subnet}s
* @param blockedAddresses
*/
@Deprecated
public void setBlockedSubnets(List<Subnet> blockedSubnets) {
this.blockedSubnets = blockedSubnets;
}
/**
* Returns the currently configured IP filter, if any.
*
* @return the currently configured IP filter, if any. Returns
* <code>null</code>, if no IP filter is configured.
*/
public IpFilter getIpFilter() {
return ipFilter;
}
/**
* Sets the IP filter to the given filter.
*
* @param ipFilter
* the IP filter.
*/
public void setIpFilter(IpFilter ipFilter) {
this.ipFilter = ipFilter;
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/ListenerFactory.java | Java | art | 9,792 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.listener;
import java.net.InetAddress;
import java.util.List;
import java.util.Set;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.ipfilter.IpFilter;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.filter.firewall.Subnet;
/**
* Interface for the component responsible for waiting for incoming socket
* requests and kicking off {@link FtpIoSession}s
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface Listener {
/**
* Start the listener, will initiate the listener waiting on the socket. The
* method should not return until the listener has started accepting socket
* requests.
* @param serverContext The current {@link FtpServerContext}
*
* @throws Exception
* On error during start up
*/
void start(FtpServerContext serverContext);
/**
* Stop the listener, it should no longer except socket requests. The method
* should not return until the listener has stopped accepting socket
* requests.
*/
void stop();
/**
* Checks if the listener is currently started.
*
* @return False if the listener is started
*/
boolean isStopped();
/**
* Temporarily stops the listener from accepting socket requests. Resume the
* listener by using the {@link #resume()} method. The method should not
* return until the listener has stopped accepting socket requests.
*/
void suspend();
/**
* Resumes a suspended listener. The method should not return until the
* listener has started accepting socket requests.
*/
void resume();
/**
* Checks if the listener is currently suspended
*
* @return True if the listener is suspended
*/
boolean isSuspended();
/**
* Returns the currently active sessions for this listener. If no sessions
* are active, an empty {@link Set} would be returned.
*
* @return The currently active sessions
*/
Set<FtpIoSession> getActiveSessions();
/**
* Is this listener in SSL mode automatically or must the client explicitly
* request to use SSL
*
* @return true is the listener is automatically in SSL mode, false
* otherwise
*/
boolean isImplicitSsl();
/**
* Get the {@link SslConfiguration} used for this listener
*
* @return The current {@link SslConfiguration}
*/
SslConfiguration getSslConfiguration();
/**
* Get the port on which this listener is waiting for requests. For
* listeners where the port is automatically assigned, this will return the
* bound port.
*
* @return The port
*/
int getPort();
/**
* Get the {@link InetAddress} used for binding the local socket. Defaults
* to null, that is, the server binds to all available network interfaces
*
* @return The local socket {@link InetAddress}, if set
*/
String getServerAddress();
/**
* Get configuration for data connections made within this listener
*
* @return The data connection configuration
*/
DataConnectionConfiguration getDataConnectionConfiguration();
/**
* Get the number of seconds during which no network activity
* is allowed before a session is closed due to inactivity.
* @return The idle time out
*/
int getIdleTimeout();
/**
* @deprecated Replaced by IpFilter. Retrieves the {@link InetAddress} for
* which this listener blocks connections.
*
* @return The list of {@link InetAddress}es. This method returns a valid
* list if and only if there is an <code>IpFilter</code> set, and,
* if it is an instance of <code>DefaultIpFilter</code> and it is of
* type <code>IpFilterType.DENY</code>. This functionality is
* provided for backward compatibility purpose only.
*/
@Deprecated
List<InetAddress> getBlockedAddresses();
/**
* @deprecated Replaced by IpFilter.
* Retrieves the {@link Subnet}s for this listener blocks connections.
*
* @return The list of {@link Subnet}s. This method returns a valid
* list if and only if there is an <code>IpFilter</code> set, and,
* if it is an instance of <code>DefaultIpFilter</code> and it is of
* type <code>IpFilterType.DENY</code>. This functionality is
* provided for backward compatibility purpose only.
*/
List<Subnet> getBlockedSubnets();
/**
* Returns the IP filter associated with this listener. May return
* <code>null</code>.
*
* @return the IP filter associated with this listener. May return
* <code>null</code>.
*/
IpFilter getIpFilter();
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/listener/Listener.java | Java | art | 5,755 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftpletcontainer;
import java.util.Map;
import org.apache.ftpserver.ftplet.Ftplet;
/**
* Interface describing an Ftplet container. Ftplet containers extend the
* {@link Ftplet} interface and forward any events to the Ftplets hosted by the
* container.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpletContainer extends Ftplet {
/**
* Retrive the {@link Ftplet} identified by the name (as provided in the
* {@link #addFtplet(String, Ftplet)} method.
*
* @param name
* The name of the Ftplet to retrive
* @return The Ftplet if found, or null if the name is unknown to the
* container.
*/
Ftplet getFtplet(String name);
/**
* Retrive all Ftplets registered with this container
*
* @return A map of all Ftplets with their name as the key
*/
Map<String, Ftplet> getFtplets();
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ftpletcontainer/FtpletContainer.java | Java | art | 1,762 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ftpletcontainer.impl;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftpletcontainer.FtpletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This ftplet calls other ftplet methods and returns appropriate return value.
*
* <strong><strong>Internal class, do not use directly.</strong></strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpletContainer implements FtpletContainer {
private final Logger LOG = LoggerFactory
.getLogger(DefaultFtpletContainer.class);
private Map<String, Ftplet> ftplets = new ConcurrentHashMap<String, Ftplet>();
public DefaultFtpletContainer() {
}
public DefaultFtpletContainer(Map<String, Ftplet> ftplets) {
this.ftplets = ftplets;
}
/**
* Get Ftplet for the given name.
*/
public synchronized Ftplet getFtplet(String name) {
if (name == null) {
return null;
}
return ftplets.get(name);
}
public synchronized void init(FtpletContext ftpletContext) throws FtpException {
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
entry.getValue().init(ftpletContext);
}
}
/**
* @see FtpletContainer#getFtplets()
*/
public synchronized Map<String, Ftplet> getFtplets() {
return ftplets;
}
/**
* Destroy all ftplets.
*/
public void destroy() {
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
try {
entry.getValue().destroy();
} catch (Exception ex) {
LOG.error(entry.getKey() + " :: FtpletHandler.destroy()", ex);
}
}
}
/**
* Call ftplet onConnect.
*/
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
FtpletResult retVal = FtpletResult.DEFAULT;
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
retVal = entry.getValue().onConnect(session);
if (retVal == null) {
retVal = FtpletResult.DEFAULT;
}
// proceed only if the return value is FtpletResult.DEFAULT
if (retVal != FtpletResult.DEFAULT) {
break;
}
}
return retVal;
}
/**
* Call ftplet onDisconnect.
*/
public FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException {
FtpletResult retVal = FtpletResult.DEFAULT;
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
retVal = entry.getValue().onDisconnect(session);
if (retVal == null) {
retVal = FtpletResult.DEFAULT;
}
// proceed only if the return value is FtpletResult.DEFAULT
if (retVal != FtpletResult.DEFAULT) {
break;
}
}
return retVal;
}
public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply)
throws FtpException, IOException {
FtpletResult retVal = FtpletResult.DEFAULT;
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
retVal = entry.getValue().afterCommand(session, request, reply);
if (retVal == null) {
retVal = FtpletResult.DEFAULT;
}
// proceed only if the return value is FtpletResult.DEFAULT
if (retVal != FtpletResult.DEFAULT) {
break;
}
}
return retVal;
}
public FtpletResult beforeCommand(FtpSession session, FtpRequest request)
throws FtpException, IOException {
FtpletResult retVal = FtpletResult.DEFAULT;
for (Entry<String, Ftplet> entry : ftplets.entrySet()) {
retVal = entry.getValue().beforeCommand(session, request);
if (retVal == null) {
retVal = FtpletResult.DEFAULT;
}
// proceed only if the return value is FtpletResult.DEFAULT
if (retVal != FtpletResult.DEFAULT) {
break;
}
}
return retVal;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ftpletcontainer/impl/DefaultFtpletContainer.java | Java | art | 5,545 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>Ftplet container implementation</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ftpletcontainer/impl/package.html | HTML | art | 982 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Various util methods for the Spring config parsing and configuration
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SpringUtil {
/**
* Get all child elements for the element
*
* @param elm
* The element for which to locate children
* @return All children
*/
public static List<Element> getChildElements(final Element elm) {
List<Element> elements = new ArrayList<Element>();
NodeList childs = elm.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
Node child = childs.item(i);
if (child instanceof Element) {
elements.add((Element) child);
}
}
return elements;
}
/**
* Get the first child element matching the local name and namespace
*
* @param parent
* The element for which to locate the child
* @param ns
* The namespace to match, or null for any namespace
* @param localName
* The local name to match, or null for any local name
* @return The first child matching the criteria
*/
public static Element getChildElement(final Element parent,
final String ns, final String localName) {
List<Element> elements = getChildElements(parent);
for (Element element : elements) {
if ((ns == null || ns.equals(element.getNamespaceURI())
&& (localName == null || localName.equals(element
.getLocalName())))) {
return element;
}
}
return null;
}
/**
* Get the text context of first child element matching the local name and
* namespace
*
* @param parent
* The element for which to locate the child
* @param ns
* The namespace to match, or null for any namespace
* @param localName
* The local name to match, or null for any local name
* @return The text content of the first child matching the criteria or null
* if element not found
*/
public static String getChildElementText(final Element parent,
final String ns, final String localName) {
List<Element> elements = getChildElements(parent);
for (Element element : elements) {
if ((ns == null || ns.equals(element.getNamespaceURI())
&& (localName == null || localName.equals(element
.getLocalName())))) {
return DomUtils.getTextValue(element);
}
}
return null;
}
/**
* Parse specific Spring elements, bean and ref
*
* @param parent
* The element in which we will look for Spring elements
* @param parserContext
* The Spring parser context
* @param builder
* The Spring bean definition builder
* @return The Spring bean definition
*/
public static Object parseSpringChildElement(final Element parent,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
Element springElm = getChildElement(parent, null, null);
String ln = springElm.getLocalName();
if ("bean".equals(ln)) {
return parserContext.getDelegate().parseBeanDefinitionElement(
springElm, builder.getBeanDefinition());
} else if ("ref".equals(ln)) {
return parserContext.getDelegate().parsePropertySubElement(
springElm, builder.getBeanDefinition());
} else {
throw new FtpServerConfigurationException("Unknown spring element "
+ ln);
}
}
/**
* Parses a attribute value into a boolean. If the attribute is missing or
* has no content, a default value is returned
*
* @param parent
* The element
* @param attrName
* The attribute name
* @param defaultValue
* The default value
* @return The value, or the default value
*/
public static boolean parseBoolean(final Element parent,
final String attrName, final boolean defaultValue) {
if (StringUtils.hasText(parent.getAttribute(attrName))) {
return Boolean.parseBoolean(parent.getAttribute(attrName));
}
return defaultValue;
}
/**
* Parses a attribute value into an integer.
*
* @param parent
* The element
* @param attrName
* The attribute name
* @return The value
* @throws NumberFormatException
* If the attribute does not contain a number
*/
public static int parseInt(final Element parent, final String attrName) {
return Integer.parseInt(parent.getAttribute(attrName));
}
/**
* Parses a attribute value into an integer. If the attribute is missing or
* has no content, a default value is returned
*
* @param parent
* The element
* @param attrName
* The attribute name
* @param defaultValue
* The default value
* @return The value, or the default value
*/
public static int parseInt(final Element parent, final String attrName,
final int defaultValue) {
if (StringUtils.hasText(parent.getAttribute(attrName))) {
return Integer.parseInt(parent.getAttribute(attrName));
}
return defaultValue;
}
/**
* Return the string value of an attribute, or null if the attribute is
* missing
*
* @param parent
* The element
* @param attrName
* The attribute name
* @return The attribute string value
*/
public static String parseString(final Element parent, final String attrName) {
if (parent.hasAttribute(attrName)) {
return parent.getAttribute(attrName);
} else {
return null;
}
}
/**
* Return an attribute value as a {@link File}
*
* @param parent
* The element
* @param attrName
* The attribute name
* @return The file representing the path used in the attribute
*/
public static File parseFile(final Element parent, final String attrName) {
if (StringUtils.hasText(parent.getAttribute(attrName))) {
return new File(parent.getAttribute(attrName));
}
return null;
}
/**
* Return an attribute value as an {@link InetAddress}
*
* @param parent
* The element
* @param attrName
* The attribute name
* @return The attribute value parsed into a {@link InetAddress}
*/
public static InetAddress parseInetAddress(final Element parent,
final String attrName) {
if (StringUtils.hasText(parent.getAttribute(attrName))) {
try {
return InetAddress.getByName(parent.getAttribute(attrName));
} catch (UnknownHostException e) {
throw new FtpServerConfigurationException("Unknown host", e);
}
}
return null;
}
/**
* Return an attribute value after checking it is a valid {@link InetAddress}
*
* @param parent
* The element
* @param attrName
* The attribute name
* @return The attribute string value.
*/
public static String parseStringFromInetAddress(final Element parent,
final String attrName){
if ( parseInetAddress(parent, attrName)!=null){
return parent.getAttribute(attrName);
}
return null;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/SpringUtil.java | Java | art | 9,194 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>Support classes for Spring based XML configuration</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/package.html | HTML | art | 1,001 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ipfilter.DefaultIpFilter;
import org.apache.ftpserver.ipfilter.IpFilterType;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.ftpserver.ssl.SslConfigurationFactory;
import org.apache.mina.filter.firewall.Subnet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Parses the FtpServer "nio-listener" element into a Spring bean graph
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ListenerBeanDefinitionParser extends
AbstractSingleBeanDefinitionParser {
private final Logger LOG = LoggerFactory
.getLogger(ListenerBeanDefinitionParser.class);
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getBeanClass(final Element element) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void doParse(final Element element,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(ListenerFactory.class);
if (StringUtils.hasText(element.getAttribute("port"))) {
factoryBuilder.addPropertyValue("port", Integer.parseInt(element
.getAttribute("port")));
}
SslConfiguration ssl = parseSsl(element);
if (ssl != null) {
factoryBuilder.addPropertyValue("sslConfiguration", ssl);
}
Element dataConElm = SpringUtil.getChildElement(element,
FtpServerNamespaceHandler.FTPSERVER_NS, "data-connection");
DataConnectionConfiguration dc = parseDataConnection(dataConElm, ssl);
factoryBuilder.addPropertyValue("dataConnectionConfiguration", dc);
if (StringUtils.hasText(element.getAttribute("idle-timeout"))) {
factoryBuilder.addPropertyValue("idleTimeout", SpringUtil.parseInt(
element, "idle-timeout", 300));
}
String localAddress = SpringUtil.parseStringFromInetAddress(element,
"local-address");
if (localAddress != null) {
factoryBuilder.addPropertyValue("serverAddress", localAddress);
}
factoryBuilder.addPropertyValue("implicitSsl", SpringUtil.parseBoolean(
element, "implicit-ssl", false));
Element blacklistElm = SpringUtil.getChildElement(element,
FtpServerNamespaceHandler.FTPSERVER_NS, "blacklist");
if (blacklistElm != null) {
LOG.warn("Element 'blacklist' is deprecated, and may be removed in a future release. Please use 'ip-filter' instead. ");
try {
DefaultIpFilter ipFilter = new DefaultIpFilter(IpFilterType.DENY, blacklistElm.getTextContent());
factoryBuilder.addPropertyValue("ipFilter", ipFilter);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid IP address or subnet in the 'blacklist' element", e);
}
}
Element ipFilterElement = SpringUtil.getChildElement(element, FtpServerNamespaceHandler.FTPSERVER_NS, "ip-filter");
if(ipFilterElement != null) {
if(blacklistElm != null) {
throw new FtpServerConfigurationException("Element 'ipFilter' may not be used when 'blacklist' element is specified. ");
}
String filterType = ipFilterElement.getAttribute("type");
try {
DefaultIpFilter ipFilter = new DefaultIpFilter(IpFilterType.parse(filterType), ipFilterElement.getTextContent());
factoryBuilder.addPropertyValue("ipFilter", ipFilter);
}
catch (UnknownHostException e) {
throw new IllegalArgumentException("Invalid IP address or subnet in the 'ip-filter' element");
}
}
BeanDefinition factoryDefinition = factoryBuilder.getBeanDefinition();
String listenerFactoryName = parserContext.getReaderContext().generateBeanName(factoryDefinition);
BeanDefinitionHolder factoryHolder = new BeanDefinitionHolder(factoryDefinition, listenerFactoryName);
registerBeanDefinition(factoryHolder, parserContext.getRegistry());
// set the factory on the listener bean
builder.getRawBeanDefinition().setFactoryBeanName(listenerFactoryName);
builder.getRawBeanDefinition().setFactoryMethodName("createListener");
}
private SslConfiguration parseSsl(final Element parent) {
Element sslElm = SpringUtil.getChildElement(parent,
FtpServerNamespaceHandler.FTPSERVER_NS, "ssl");
if (sslElm != null) {
SslConfigurationFactory ssl = new SslConfigurationFactory();
Element keyStoreElm = SpringUtil.getChildElement(sslElm,
FtpServerNamespaceHandler.FTPSERVER_NS, "keystore");
if (keyStoreElm != null) {
ssl.setKeystoreFile(SpringUtil.parseFile(keyStoreElm, "file"));
ssl.setKeystorePassword(SpringUtil.parseString(keyStoreElm,
"password"));
String type = SpringUtil.parseString(keyStoreElm, "type");
if (type != null) {
ssl.setKeystoreType(type);
}
String keyAlias = SpringUtil.parseString(keyStoreElm,
"key-alias");
if (keyAlias != null) {
ssl.setKeyAlias(keyAlias);
}
String keyPassword = SpringUtil.parseString(keyStoreElm,
"key-password");
if (keyPassword != null) {
ssl.setKeyPassword(keyPassword);
}
String algorithm = SpringUtil.parseString(keyStoreElm,
"algorithm");
if (algorithm != null) {
ssl.setKeystoreAlgorithm(algorithm);
}
}
Element trustStoreElm = SpringUtil.getChildElement(sslElm,
FtpServerNamespaceHandler.FTPSERVER_NS, "truststore");
if (trustStoreElm != null) {
ssl.setTruststoreFile(SpringUtil.parseFile(trustStoreElm,
"file"));
ssl.setTruststorePassword(SpringUtil.parseString(trustStoreElm,
"password"));
String type = SpringUtil.parseString(trustStoreElm, "type");
if (type != null) {
ssl.setTruststoreType(type);
}
String algorithm = SpringUtil.parseString(trustStoreElm,
"algorithm");
if (algorithm != null) {
ssl.setTruststoreAlgorithm(algorithm);
}
}
String clientAuthStr = SpringUtil.parseString(sslElm,
"client-authentication");
if (clientAuthStr != null) {
ssl.setClientAuthentication(clientAuthStr);
}
String enabledCiphersuites = SpringUtil.parseString(sslElm,
"enabled-ciphersuites");
if (enabledCiphersuites != null) {
ssl.setEnabledCipherSuites(enabledCiphersuites.split(" "));
}
String protocol = SpringUtil.parseString(sslElm, "protocol");
if (protocol != null) {
ssl.setSslProtocol(protocol);
}
return ssl.createSslConfiguration();
} else {
return null;
}
}
private DataConnectionConfiguration parseDataConnection(
final Element element,
final SslConfiguration listenerSslConfiguration) {
DataConnectionConfigurationFactory dc = new DataConnectionConfigurationFactory();
if (element != null) {
dc.setImplicitSsl(SpringUtil.parseBoolean(element, "implicit-ssl", false));
// data con config element available
SslConfiguration ssl = parseSsl(element);
if (ssl != null) {
LOG.debug("SSL configuration found for the data connection");
dc.setSslConfiguration(ssl);
}
dc.setIdleTime(SpringUtil.parseInt(element, "idle-timeout", dc.getIdleTime()));
Element activeElm = SpringUtil.getChildElement(element,
FtpServerNamespaceHandler.FTPSERVER_NS, "active");
if (activeElm != null) {
dc.setActiveEnabled(SpringUtil.parseBoolean(activeElm, "enabled",
true));
dc.setActiveIpCheck(SpringUtil.parseBoolean(activeElm,
"ip-check", false));
dc.setActiveLocalPort(SpringUtil.parseInt(activeElm,
"local-port", 0));
String localAddress = SpringUtil.parseStringFromInetAddress(
activeElm, "local-address");
if (localAddress != null) {
dc.setActiveLocalAddress(localAddress);
}
}
Element passiveElm = SpringUtil.getChildElement(element,
FtpServerNamespaceHandler.FTPSERVER_NS, "passive");
if (passiveElm != null) {
String address = SpringUtil.parseStringFromInetAddress(passiveElm,
"address");
if (address != null) {
dc.setPassiveAddress(address);
}
String externalAddress = SpringUtil.parseStringFromInetAddress(
passiveElm, "external-address");
if (externalAddress != null) {
dc.setPassiveExternalAddress(externalAddress);
}
String ports = SpringUtil.parseString(passiveElm, "ports");
if (ports != null) {
dc.setPassivePorts(ports);
}
}
} else {
// no data conn config element, do we still have SSL config from the
// parent?
if (listenerSslConfiguration != null) {
LOG
.debug("SSL configuration found for the listener, falling back for that for the data connection");
dc.setSslConfiguration(listenerSslConfiguration);
}
}
return dc.createDataConnectionConfiguration();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/ListenerBeanDefinitionParser.java | Java | art | 12,279 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.ftpserver.ConnectionConfigFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.message.MessageResource;
import org.apache.ftpserver.message.MessageResourceFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Parses the FtpServer "server" element into a Spring bean graph
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ServerBeanDefinitionParser extends
AbstractSingleBeanDefinitionParser {
/**
* {@inheritDoc}
*/
protected Class<? extends FtpServer> getBeanClass(final Element element) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void doParse(final Element element,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(FtpServerFactory.class);
List<Element> childs = SpringUtil.getChildElements(element);
for (Element childElm : childs) {
String childName = childElm.getLocalName();
if ("listeners".equals(childName)) {
Map listeners = parseListeners(childElm, parserContext, builder);
if (listeners.size() > 0) {
factoryBuilder.addPropertyValue("listeners", listeners);
}
} else if ("ftplets".equals(childName)) {
Map ftplets = parseFtplets(childElm, parserContext, builder);
factoryBuilder.addPropertyValue("ftplets", ftplets);
} else if ("file-user-manager".equals(childName)
|| "db-user-manager".equals(childName)) {
Object userManager = parserContext.getDelegate()
.parseCustomElement(childElm,
builder.getBeanDefinition());
factoryBuilder.addPropertyValue("userManager", userManager);
} else if ("user-manager".equals(childName)) {
factoryBuilder.addPropertyValue("userManager", SpringUtil
.parseSpringChildElement(childElm, parserContext,
builder));
} else if ("native-filesystem".equals(childName)) {
Object fileSystem = parserContext.getDelegate()
.parseCustomElement(childElm,
builder.getBeanDefinition());
factoryBuilder.addPropertyValue("fileSystem", fileSystem);
} else if ("filesystem".equals(childName)) {
factoryBuilder.addPropertyValue("fileSystem", SpringUtil
.parseSpringChildElement(childElm, parserContext,
builder));
} else if ("commands".equals(childName)) {
Object commandFactory = parserContext.getDelegate()
.parseCustomElement(childElm,
builder.getBeanDefinition());
factoryBuilder.addPropertyValue("commandFactory", commandFactory);
} else if ("messages".equals(childName)) {
MessageResource mr = parseMessageResource(childElm,
parserContext, builder);
factoryBuilder.addPropertyValue("messageResource", mr);
} else {
throw new FtpServerConfigurationException(
"Unknown configuration name: " + childName);
}
}
// Configure login limits
ConnectionConfigFactory connectionConfig = new ConnectionConfigFactory();
if (StringUtils.hasText(element.getAttribute("max-logins"))) {
connectionConfig.setMaxLogins(SpringUtil.parseInt(element,
"max-logins"));
}
if (StringUtils.hasText(element.getAttribute("max-threads"))) {
connectionConfig.setMaxThreads(SpringUtil.parseInt(element,
"max-threads"));
}
if (StringUtils.hasText(element.getAttribute("max-anon-logins"))) {
connectionConfig.setMaxAnonymousLogins(SpringUtil.parseInt(element,
"max-anon-logins"));
}
if (StringUtils.hasText(element.getAttribute("anon-enabled"))) {
connectionConfig.setAnonymousLoginEnabled(SpringUtil.parseBoolean(
element, "anon-enabled", true));
}
if (StringUtils.hasText(element.getAttribute("max-login-failures"))) {
connectionConfig.setMaxLoginFailures(SpringUtil.parseInt(element,
"max-login-failures"));
}
if (StringUtils.hasText(element.getAttribute("login-failure-delay"))) {
connectionConfig.setLoginFailureDelay(SpringUtil.parseInt(element,
"login-failure-delay"));
}
factoryBuilder.addPropertyValue("connectionConfig", connectionConfig.createConnectionConfig());
BeanDefinition factoryDefinition = factoryBuilder.getBeanDefinition();
String factoryName = parserContext.getReaderContext().generateBeanName(factoryDefinition);
BeanDefinitionHolder factoryHolder = new BeanDefinitionHolder(factoryDefinition, factoryName);
registerBeanDefinition(factoryHolder, parserContext.getRegistry());
// set the factory on the listener bean
builder.getRawBeanDefinition().setFactoryBeanName(factoryName);
builder.getRawBeanDefinition().setFactoryMethodName("createServer");
}
/**
* Parse the "messages" element
*/
private MessageResource parseMessageResource(final Element childElm,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
MessageResourceFactory mr = new MessageResourceFactory();
if (StringUtils.hasText(childElm.getAttribute("languages"))) {
String langString = childElm.getAttribute("languages");
String[] languages = langString.split("[\\s,]+");
mr.setLanguages(Arrays.asList(languages));
}
if (StringUtils.hasText(childElm.getAttribute("directory"))) {
mr.setCustomMessageDirectory(new File(childElm
.getAttribute("directory")));
}
return mr.createMessageResource();
}
/**
* Parse the "ftplets" element
*/
private Map parseFtplets(final Element childElm,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
List<Element> childs = SpringUtil.getChildElements(childElm);
if(childs.size() > 0 && childs.get(0).getLocalName().equals("map")) {
// using a beans:map element
return (Map) parserContext.getDelegate().parseMapElement(
childs.get(0),
builder.getBeanDefinition());
} else {
ManagedMap ftplets = new ManagedMap();
for (Element ftpletElm : childs) {
ftplets
.put(ftpletElm.getAttribute("name"), SpringUtil
.parseSpringChildElement(ftpletElm, parserContext,
builder));
}
return ftplets;
}
}
/**
* Parse listeners elements
*/
@SuppressWarnings("unchecked")
private Map parseListeners(final Element listenersElm,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
ManagedMap listeners = new ManagedMap();
List<Element> childs = SpringUtil.getChildElements(listenersElm);
for (Element listenerElm : childs) {
Object listener = null;
String ln = listenerElm.getLocalName();
if ("nio-listener".equals(ln)) {
listener = parserContext.getDelegate().parseCustomElement(
listenerElm, builder.getBeanDefinition());
} else if ("listener".equals(ln)) {
listener = SpringUtil.parseSpringChildElement(listenerElm,
parserContext, builder);
} else {
throw new FtpServerConfigurationException(
"Unknown listener element " + ln);
}
String name = listenerElm.getAttribute("name");
listeners.put(name, listener);
}
return listeners;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/ServerBeanDefinitionParser.java | Java | art | 9,981 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import java.util.List;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.command.CommandFactoryFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Parses the FtpServer "commands" element into a Spring bean graph
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class CommandFactoryBeanDefinitionParser extends
AbstractSingleBeanDefinitionParser {
/**
* {@inheritDoc}
*/
@Override
protected Class<? extends CommandFactory> getBeanClass(final Element element) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void doParse(final Element element,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(CommandFactoryFactory.class);
ManagedMap commands = new ManagedMap();
List<Element> childs = SpringUtil.getChildElements(element);
for (Element commandElm : childs) {
String name = commandElm.getAttribute("name");
Object bean = SpringUtil.parseSpringChildElement(commandElm,
parserContext, builder);
commands.put(name, bean);
}
factoryBuilder.addPropertyValue("commandMap", commands);
if (StringUtils.hasText(element.getAttribute("use-default"))) {
factoryBuilder.addPropertyValue("useDefaultCommands", Boolean
.parseBoolean(element.getAttribute("use-default")));
}
BeanDefinition factoryDefinition = factoryBuilder.getBeanDefinition();
String factoryId = parserContext.getReaderContext().generateBeanName(factoryDefinition);
BeanDefinitionHolder factoryHolder = new BeanDefinitionHolder(factoryDefinition, factoryId);
registerBeanDefinition(factoryHolder, parserContext.getRegistry());
// set the factory on the listener bean
builder.getRawBeanDefinition().setFactoryBeanName(factoryId);
builder.getRawBeanDefinition().setFactoryMethodName("createCommandFactory");
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/CommandFactoryBeanDefinitionParser.java | Java | art | 3,488 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.DbUserManagerFactory;
import org.apache.ftpserver.usermanager.Md5PasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Parses the FtpServer "file-user-manager" or "db-user-manager" elements into a
* Spring bean graph
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class UserManagerBeanDefinitionParser extends
AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(final Element element) {
return null;
}
@Override
protected void doParse(final Element element,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
Class factoryClass;
if (element.getLocalName().equals("file-user-manager")) {
factoryClass = PropertiesUserManagerFactory.class;
} else {
factoryClass = DbUserManagerFactory.class;
}
BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(factoryClass);
// common for both user managers
if (StringUtils.hasText(element.getAttribute("encrypt-passwords"))) {
String encryptionStrategy = element.getAttribute("encrypt-passwords");
if(encryptionStrategy.equals("true") || encryptionStrategy.equals("md5")) {
factoryBuilder.addPropertyValue("passwordEncryptor", new Md5PasswordEncryptor());
} else if(encryptionStrategy.equals("salted")) {
factoryBuilder.addPropertyValue("passwordEncryptor", new SaltedPasswordEncryptor());
} else {
factoryBuilder.addPropertyValue("passwordEncryptor", new ClearTextPasswordEncryptor());
}
}
if (factoryClass == PropertiesUserManagerFactory.class) {
if (StringUtils.hasText(element.getAttribute("file"))) {
factoryBuilder.addPropertyValue("file", element.getAttribute("file"));
}
if (StringUtils.hasText(element.getAttribute("url"))) {
factoryBuilder.addPropertyValue("url", element.getAttribute("url"));
}
} else {
Element dsElm = SpringUtil.getChildElement(element,
FtpServerNamespaceHandler.FTPSERVER_NS, "data-source");
// schema ensure we get the right type of element
Element springElm = SpringUtil.getChildElement(dsElm, null, null);
Object o;
if ("bean".equals(springElm.getLocalName())) {
o = parserContext.getDelegate().parseBeanDefinitionElement(
springElm, builder.getBeanDefinition());
} else {
// ref
o = parserContext.getDelegate().parsePropertySubElement(
springElm, builder.getBeanDefinition());
}
factoryBuilder.addPropertyValue("dataSource", o);
factoryBuilder.addPropertyValue("sqlUserInsert", getSql(element,
"insert-user"));
factoryBuilder.addPropertyValue("sqlUserUpdate", getSql(element,
"update-user"));
factoryBuilder.addPropertyValue("sqlUserDelete", getSql(element,
"delete-user"));
factoryBuilder.addPropertyValue("sqlUserSelect", getSql(element,
"select-user"));
factoryBuilder.addPropertyValue("sqlUserSelectAll", getSql(element,
"select-all-users"));
factoryBuilder.addPropertyValue("sqlUserAdmin",
getSql(element, "is-admin"));
factoryBuilder.addPropertyValue("sqlUserAuthenticate", getSql(element,
"authenticate"));
}
BeanDefinition factoryDefinition = factoryBuilder.getBeanDefinition();
String factoryId = parserContext.getReaderContext().generateBeanName(factoryDefinition);
BeanDefinitionHolder factoryHolder = new BeanDefinitionHolder(factoryDefinition, factoryId);
registerBeanDefinition(factoryHolder, parserContext.getRegistry());
// set the factory on the listener bean
builder.getRawBeanDefinition().setFactoryBeanName(factoryId);
builder.getRawBeanDefinition().setFactoryMethodName("createUserManager");
}
private String getSql(final Element element, final String elmName) {
return SpringUtil.getChildElementText(element,
FtpServerNamespaceHandler.FTPSERVER_NS, elmName);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/UserManagerBeanDefinitionParser.java | Java | art | 6,002 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Parses the FtpServer "native-filesystem" element into a Spring bean graph
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FileSystemBeanDefinitionParser extends
AbstractSingleBeanDefinitionParser {
/**
* {@inheritDoc}
*/
@Override
protected Class<? extends FileSystemFactory> getBeanClass(
final Element element) {
return NativeFileSystemFactory.class;
}
/**
* {@inheritDoc}
*/
@Override
protected void doParse(final Element element,
final ParserContext parserContext,
final BeanDefinitionBuilder builder) {
if (StringUtils.hasText(element.getAttribute("case-insensitive"))) {
builder.addPropertyValue("caseInsensitive", Boolean
.parseBoolean(element.getAttribute("case-insensitive")));
}
if (StringUtils.hasText(element.getAttribute("create-home"))) {
builder.addPropertyValue("createHome", Boolean
.parseBoolean(element.getAttribute("create-home")));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/FileSystemBeanDefinitionParser.java | Java | art | 2,375 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.config.spring;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
/**
* Registration point for FtpServer bean defintion parsers
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpServerNamespaceHandler extends NamespaceHandlerSupport {
/**
* The FtpServer Spring config namespace
*/
public static final String FTPSERVER_NS = "http://mina.apache.org/ftpserver/spring/v1";
/**
* Register the necessary element names with the appropriate bean definition
* parser
*/
public FtpServerNamespaceHandler() {
registerBeanDefinitionParser("server", new ServerBeanDefinitionParser());
registerBeanDefinitionParser("nio-listener",
new ListenerBeanDefinitionParser());
registerBeanDefinitionParser("file-user-manager",
new UserManagerBeanDefinitionParser());
registerBeanDefinitionParser("db-user-manager",
new UserManagerBeanDefinitionParser());
registerBeanDefinitionParser("native-filesystem",
new FileSystemBeanDefinitionParser());
registerBeanDefinitionParser("commands",
new CommandFactoryBeanDefinitionParser());
}
/**
* {@inheritDoc}
*/
public void init() {
// do nothing
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/config/spring/FtpServerNamespaceHandler.java | Java | art | 2,178 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver;
import org.apache.ftpserver.impl.DefaultConnectionConfig;
/**
* Factory for creating connection configurations
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ConnectionConfigFactory {
private int maxLogins = 10;
private boolean anonymousLoginEnabled = true;
private int maxAnonymousLogins = 10;
private int maxLoginFailures = 3;
private int loginFailureDelay = 500;
private int maxThreads = 0;
/**
* Create a connection configuration instances based on the configuration on this factory
* @return The {@link ConnectionConfig} instance
*/
public ConnectionConfig createConnectionConfig() {
return new DefaultConnectionConfig(anonymousLoginEnabled,
loginFailureDelay, maxLogins, maxAnonymousLogins,
maxLoginFailures, maxThreads);
}
/**
* The delay in number of milliseconds between login failures. Important to
* make brute force attacks harder.
*
* @return The delay time in milliseconds
*/
public int getLoginFailureDelay() {
return loginFailureDelay;
}
/**
* The maximum number of anonymous logins the server would allow at any given time
* @return The maximum number of anonymous logins
*/
public int getMaxAnonymousLogins() {
return maxAnonymousLogins;
}
/**
* The maximum number of time an user can fail to login before getting disconnected
* @return The maximum number of failure login attempts
*/
public int getMaxLoginFailures() {
return maxLoginFailures;
}
/**
* The maximum number of concurrently logged in users
* @return The maximum number of users
*/
public int getMaxLogins() {
return maxLogins;
}
/**
* Is anonymous logins allowed at the server?
* @return true if anonymous logins are enabled
*/
public boolean isAnonymousLoginEnabled() {
return anonymousLoginEnabled;
}
/**
* Set she maximum number of concurrently logged in users
* @param maxLogins The maximum number of users
*/
public void setMaxLogins(final int maxLogins) {
this.maxLogins = maxLogins;
}
/**
* Returns the maximum number of threads the server is allowed to create for
* processing client requests.
*
* @return the maximum number of threads the server is allowed to create for
* processing client requests.
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* Sets the maximum number of threads the server is allowed to create for
* processing client requests.
*
* @param maxThreads
* the maximum number of threads the server is allowed to create
* for processing client requests.
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/**
* Set if anonymous logins are allowed at the server
* @param anonymousLoginEnabled true if anonymous logins should be enabled
*/
public void setAnonymousLoginEnabled(final boolean anonymousLoginEnabled) {
this.anonymousLoginEnabled = anonymousLoginEnabled;
}
/**
* Sets the maximum number of anonymous logins the server would allow at any given time
* @param maxAnonymousLogins The maximum number of anonymous logins
*/
public void setMaxAnonymousLogins(final int maxAnonymousLogins) {
this.maxAnonymousLogins = maxAnonymousLogins;
}
/**
* Set the maximum number of time an user can fail to login before getting disconnected
* @param maxLoginFailures The maximum number of failure login attempts
*/
public void setMaxLoginFailures(final int maxLoginFailures) {
this.maxLoginFailures = maxLoginFailures;
}
/**
* Set the delay in number of milliseconds between login failures. Important to
* make brute force attacks harder.
*
* @param loginFailureDelay The delay time in milliseconds
*/
public void setLoginFailureDelay(final int loginFailureDelay) {
this.loginFailureDelay = loginFailureDelay;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ConnectionConfigFactory.java | Java | art | 5,058 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.filesystem.nativefs;
import java.io.File;
import org.apache.ftpserver.filesystem.nativefs.impl.NativeFileSystemView;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Native file system factory. It uses the OS file system.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NativeFileSystemFactory implements FileSystemFactory {
private final Logger LOG = LoggerFactory
.getLogger(NativeFileSystemFactory.class);
private boolean createHome;
private boolean caseInsensitive;
/**
* Should the home directories be created automatically
* @return true if the file system will create the home directory if not available
*/
public boolean isCreateHome() {
return createHome;
}
/**
* Set if the home directories be created automatically
* @param createHome true if the file system will create the home directory if not available
*/
public void setCreateHome(boolean createHome) {
this.createHome = createHome;
}
/**
* Is this file system case insensitive.
* Enabling might cause problems when working against case-sensitive file systems, like on Linux
* @return true if this file system is case insensitive
*/
public boolean isCaseInsensitive() {
return caseInsensitive;
}
/**
* Should this file system be case insensitive.
* Enabling might cause problems when working against case-sensitive file systems, like on Linux
* @param caseInsensitive true if this file system should be case insensitive
*/
public void setCaseInsensitive(boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive;
}
/**
* Create the appropriate user file system view.
*/
public FileSystemView createFileSystemView(User user) throws FtpException {
synchronized (user) {
// create home if does not exist
if (createHome) {
String homeDirStr = user.getHomeDirectory();
File homeDir = new File(homeDirStr);
if (homeDir.isFile()) {
LOG.warn("Not a directory :: " + homeDirStr);
throw new FtpException("Not a directory :: " + homeDirStr);
}
if ((!homeDir.exists()) && (!homeDir.mkdirs())) {
LOG.warn("Cannot create user home :: " + homeDirStr);
throw new FtpException("Cannot create user home :: "
+ homeDirStr);
}
}
FileSystemView fsView = new NativeFileSystemView(user,
caseInsensitive);
return fsView;
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/filesystem/nativefs/NativeFileSystemFactory.java | Java | art | 3,776 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.filesystem.nativefs.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.impl.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This class wraps native file object.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NativeFtpFile implements FtpFile {
private final Logger LOG = LoggerFactory.getLogger(NativeFtpFile.class);
// the file name with respect to the user root.
// The path separator character will be '/' and
// it will always begin with '/'.
private String fileName;
private File file;
private User user;
/**
* Constructor, internal do not use directly.
*/
protected NativeFtpFile(final String fileName, final File file,
final User user) {
if (fileName == null) {
throw new IllegalArgumentException("fileName can not be null");
}
if (file == null) {
throw new IllegalArgumentException("file can not be null");
}
if (fileName.length() == 0) {
throw new IllegalArgumentException("fileName can not be empty");
} else if (fileName.charAt(0) != '/') {
throw new IllegalArgumentException(
"fileName must be an absolut path");
}
this.fileName = fileName;
this.file = file;
this.user = user;
}
/**
* Get full name.
*/
public String getAbsolutePath() {
// strip the last '/' if necessary
String fullName = fileName;
int filelen = fullName.length();
if ((filelen != 1) && (fullName.charAt(filelen - 1) == '/')) {
fullName = fullName.substring(0, filelen - 1);
}
return fullName;
}
/**
* Get short name.
*/
public String getName() {
// root - the short name will be '/'
if (fileName.equals("/")) {
return "/";
}
// strip the last '/'
String shortName = fileName;
int filelen = fileName.length();
if (shortName.charAt(filelen - 1) == '/') {
shortName = shortName.substring(0, filelen - 1);
}
// return from the last '/'
int slashIndex = shortName.lastIndexOf('/');
if (slashIndex != -1) {
shortName = shortName.substring(slashIndex + 1);
}
return shortName;
}
/**
* Is a hidden file?
*/
public boolean isHidden() {
return file.isHidden();
}
/**
* Is it a directory?
*/
public boolean isDirectory() {
return file.isDirectory();
}
/**
* Is it a file?
*/
public boolean isFile() {
return file.isFile();
}
/**
* Does this file exists?
*/
public boolean doesExist() {
return file.exists();
}
/**
* Get file size.
*/
public long getSize() {
return file.length();
}
/**
* Get file owner.
*/
public String getOwnerName() {
return "user";
}
/**
* Get group name
*/
public String getGroupName() {
return "group";
}
/**
* Get link count
*/
public int getLinkCount() {
return file.isDirectory() ? 3 : 1;
}
/**
* Get last modified time.
*/
public long getLastModified() {
return file.lastModified();
}
/**
* {@inheritDoc}
*/
public boolean setLastModified(long time) {
return file.setLastModified(time);
}
/**
* Check read permission.
*/
public boolean isReadable() {
return file.canRead();
}
/**
* Check file write permission.
*/
public boolean isWritable() {
LOG.debug("Checking authorization for " + getAbsolutePath());
if (user.authorize(new WriteRequest(getAbsolutePath())) == null) {
LOG.debug("Not authorized");
return false;
}
LOG.debug("Checking if file exists");
if (file.exists()) {
LOG.debug("Checking can write: " + file.canWrite());
return file.canWrite();
}
LOG.debug("Authorized");
return true;
}
/**
* Has delete permission.
*/
public boolean isRemovable() {
// root cannot be deleted
if ("/".equals(fileName)) {
return false;
}
/* Added 12/08/2008: in the case that the permission is not explicitly denied for this file
* we will check if the parent file has write permission as most systems consider that a file can
* be deleted when their parent directory is writable.
*/
String fullName = getAbsolutePath();
// we check FTPServer's write permission for this file.
if (user.authorize(new WriteRequest(fullName)) == null) {
return false;
}
// In order to maintain consistency, when possible we delete the last '/' character in the String
int indexOfSlash = fullName.lastIndexOf('/');
String parentFullName;
if (indexOfSlash == 0) {
parentFullName = "/";
} else {
parentFullName = fullName.substring(0, indexOfSlash);
}
// we check if the parent FileObject is writable.
NativeFtpFile parentObject = new NativeFtpFile(parentFullName, file
.getAbsoluteFile().getParentFile(), user);
return parentObject.isWritable();
}
/**
* Delete file.
*/
public boolean delete() {
boolean retVal = false;
if (isRemovable()) {
retVal = file.delete();
}
return retVal;
}
/**
* Move file object.
*/
public boolean move(final FtpFile dest) {
boolean retVal = false;
if (dest.isWritable() && isReadable()) {
File destFile = ((NativeFtpFile) dest).file;
if (destFile.exists()) {
// renameTo behaves differently on different platforms
// this check verifies that if the destination already exists,
// we fail
retVal = false;
} else {
retVal = file.renameTo(destFile);
}
}
return retVal;
}
/**
* Create directory.
*/
public boolean mkdir() {
boolean retVal = false;
if (isWritable()) {
retVal = file.mkdir();
}
return retVal;
}
/**
* Get the physical file object.
*/
public File getPhysicalFile() {
return file;
}
/**
* List files. If not a directory or does not exist, null will be returned.
*/
public List<FtpFile> listFiles() {
// is a directory
if (!file.isDirectory()) {
return null;
}
// directory - return all the files
File[] files = file.listFiles();
if (files == null) {
return null;
}
// make sure the files are returned in order
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
});
// get the virtual name of the base directory
String virtualFileStr = getAbsolutePath();
if (virtualFileStr.charAt(virtualFileStr.length() - 1) != '/') {
virtualFileStr += '/';
}
// now return all the files under the directory
FtpFile[] virtualFiles = new FtpFile[files.length];
for (int i = 0; i < files.length; ++i) {
File fileObj = files[i];
String fileName = virtualFileStr + fileObj.getName();
virtualFiles[i] = new NativeFtpFile(fileName, fileObj, user);
}
return Collections.unmodifiableList(Arrays.asList(virtualFiles));
}
/**
* Create output stream for writing.
*/
public OutputStream createOutputStream(final long offset)
throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + file.getName());
}
// create output stream
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(offset);
raf.seek(offset);
// The IBM jre needs to have both the stream and the random access file
// objects closed to actually close the file
return new FileOutputStream(raf.getFD()) {
public void close() throws IOException {
super.close();
raf.close();
}
};
}
/**
* Create input stream for reading.
*/
public InputStream createInputStream(final long offset) throws IOException {
// permission check
if (!isReadable()) {
throw new IOException("No read permission : " + file.getName());
}
// move to the appropriate offset and create input stream
final RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(offset);
// The IBM jre needs to have both the stream and the random access file
// objects closed to actually close the file
return new FileInputStream(raf.getFD()) {
public void close() throws IOException {
super.close();
raf.close();
}
};
}
/**
* Normalize separate character. Separate character should be '/' always.
*/
public final static String normalizeSeparateChar(final String pathName) {
String normalizedPathName = pathName.replace(File.separatorChar, '/');
normalizedPathName = normalizedPathName.replace('\\', '/');
return normalizedPathName;
}
/**
* Get the physical canonical file name. It works like
* File.getCanonicalPath().
*
* @param rootDir
* The root directory.
* @param currDir
* The current directory. It will always be with respect to the
* root directory.
* @param fileName
* The input file name.
* @return The return string will always begin with the root directory. It
* will never be null.
*/
public final static String getPhysicalName(final String rootDir,
final String currDir, final String fileName) {
return getPhysicalName(rootDir, currDir, fileName, false);
}
public final static String getPhysicalName(final String rootDir,
final String currDir, final String fileName,
final boolean caseInsensitive) {
// get the starting directory
String normalizedRootDir = normalizeSeparateChar(rootDir);
if (normalizedRootDir.charAt(normalizedRootDir.length() - 1) != '/') {
normalizedRootDir += '/';
}
String normalizedFileName = normalizeSeparateChar(fileName);
String resArg;
String normalizedCurrDir = currDir;
if (normalizedFileName.charAt(0) != '/') {
if (normalizedCurrDir == null) {
normalizedCurrDir = "/";
}
if (normalizedCurrDir.length() == 0) {
normalizedCurrDir = "/";
}
normalizedCurrDir = normalizeSeparateChar(normalizedCurrDir);
if (normalizedCurrDir.charAt(0) != '/') {
normalizedCurrDir = '/' + normalizedCurrDir;
}
if (normalizedCurrDir.charAt(normalizedCurrDir.length() - 1) != '/') {
normalizedCurrDir += '/';
}
resArg = normalizedRootDir + normalizedCurrDir.substring(1);
} else {
resArg = normalizedRootDir;
}
// strip last '/'
if (resArg.charAt(resArg.length() - 1) == '/') {
resArg = resArg.substring(0, resArg.length() - 1);
}
// replace ., ~ and ..
// in this loop resArg will never end with '/'
StringTokenizer st = new StringTokenizer(normalizedFileName, "/");
while (st.hasMoreTokens()) {
String tok = st.nextToken();
// . => current directory
if (tok.equals(".")) {
continue;
}
// .. => parent directory (if not root)
if (tok.equals("..")) {
if (resArg.startsWith(normalizedRootDir)) {
int slashIndex = resArg.lastIndexOf('/');
if (slashIndex != -1) {
resArg = resArg.substring(0, slashIndex);
}
}
continue;
}
// ~ => home directory (in this case the root directory)
if (tok.equals("~")) {
resArg = normalizedRootDir.substring(0, normalizedRootDir
.length() - 1);
continue;
}
if (caseInsensitive) {
File[] matches = new File(resArg)
.listFiles(new NameEqualsFileFilter(tok, true));
if (matches != null && matches.length > 0) {
tok = matches[0].getName();
}
}
resArg = resArg + '/' + tok;
}
// add last slash if necessary
if ((resArg.length()) + 1 == normalizedRootDir.length()) {
resArg += '/';
}
// final check
if (!resArg.regionMatches(0, normalizedRootDir, 0, normalizedRootDir
.length())) {
resArg = normalizedRootDir;
}
return resArg;
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof NativeFtpFile) {
File thisCanonicalFile;
File otherCanonicalFile;
try {
thisCanonicalFile = this.file.getCanonicalFile();
otherCanonicalFile = ((NativeFtpFile) obj).file
.getCanonicalFile();
} catch (IOException e) {
throw new RuntimeException("Failed to get the canonical path", e);
}
return thisCanonicalFile.equals(otherCanonicalFile);
}
return false;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/filesystem/nativefs/impl/NativeFtpFile.java | Java | art | 15,613 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>Native file system implementation</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/filesystem/nativefs/impl/package.html | HTML | art | 984 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.filesystem.nativefs.impl;
import java.io.File;
import java.io.FileFilter;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FileFilter used for simple file name matching
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NameEqualsFileFilter implements FileFilter {
private String nameToMatch;
private boolean caseInsensitive = false;
/**
* Constructor
*
* @param nameToMatch
* The exact file name to match
* @param caseInsensitive
* Wether that match should be case insensitive
*/
public NameEqualsFileFilter(final String nameToMatch,
final boolean caseInsensitive) {
this.nameToMatch = nameToMatch;
this.caseInsensitive = caseInsensitive;
}
public boolean accept(final File file) {
if (caseInsensitive) {
return file.getName().equalsIgnoreCase(nameToMatch);
} else {
return file.getName().equals(nameToMatch);
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/filesystem/nativefs/impl/NameEqualsFileFilter.java | Java | art | 1,880 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.filesystem.nativefs.impl;
import java.io.File;
import org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* File system view based on native file system. Here the root directory will be
* user virtual root (/).
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NativeFileSystemView implements FileSystemView {
private final Logger LOG = LoggerFactory
.getLogger(NativeFileSystemView.class);
// the root directory will always end with '/'.
private String rootDir;
// the first and the last character will always be '/'
// It is always with respect to the root directory.
private String currDir;
private User user;
// private boolean writePermission;
private boolean caseInsensitive = false;
/**
* Constructor - internal do not use directly, use {@link NativeFileSystemFactory} instead
*/
protected NativeFileSystemView(User user) throws FtpException {
this(user, false);
}
/**
* Constructor - internal do not use directly, use {@link NativeFileSystemFactory} instead
*/
public NativeFileSystemView(User user, boolean caseInsensitive)
throws FtpException {
if (user == null) {
throw new IllegalArgumentException("user can not be null");
}
if (user.getHomeDirectory() == null) {
throw new IllegalArgumentException(
"User home directory can not be null");
}
this.caseInsensitive = caseInsensitive;
// add last '/' if necessary
String rootDir = user.getHomeDirectory();
rootDir = NativeFtpFile.normalizeSeparateChar(rootDir);
if (!rootDir.endsWith("/")) {
rootDir += '/';
}
LOG.debug("Native filesystem view created for user \"{}\" with root \"{}\"", user.getName(), rootDir);
this.rootDir = rootDir;
this.user = user;
currDir = "/";
}
/**
* Get the user home directory. It would be the file system root for the
* user.
*/
public FtpFile getHomeDirectory() {
return new NativeFtpFile("/", new File(rootDir), user);
}
/**
* Get the current directory.
*/
public FtpFile getWorkingDirectory() {
FtpFile fileObj = null;
if (currDir.equals("/")) {
fileObj = new NativeFtpFile("/", new File(rootDir), user);
} else {
File file = new File(rootDir, currDir.substring(1));
fileObj = new NativeFtpFile(currDir, file, user);
}
return fileObj;
}
/**
* Get file object.
*/
public FtpFile getFile(String file) {
// get actual file object
String physicalName = NativeFtpFile.getPhysicalName(rootDir,
currDir, file, caseInsensitive);
File fileObj = new File(physicalName);
// strip the root directory and return
String userFileName = physicalName.substring(rootDir.length() - 1);
return new NativeFtpFile(userFileName, fileObj, user);
}
/**
* Change directory.
*/
public boolean changeWorkingDirectory(String dir) {
// not a directory - return false
dir = NativeFtpFile.getPhysicalName(rootDir, currDir, dir,
caseInsensitive);
File dirObj = new File(dir);
if (!dirObj.isDirectory()) {
return false;
}
// strip user root and add last '/' if necessary
dir = dir.substring(rootDir.length() - 1);
if (dir.charAt(dir.length() - 1) != '/') {
dir = dir + '/';
}
currDir = dir;
return true;
}
/**
* Is the file content random accessible?
*/
public boolean isRandomAccessible() {
return true;
}
/**
* Dispose file system view - does nothing.
*/
public void dispose() {
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/filesystem/nativefs/impl/NativeFileSystemView.java | Java | art | 5,080 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver;
/**
* Interface for providing the configuration for the control socket connections.
*
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface ConnectionConfig {
/**
* The maximum number of time an user can fail to login before getting disconnected
* @return The maximum number of failure login attempts
*/
int getMaxLoginFailures();
/**
* The delay in number of milliseconds between login failures. Important to
* make brute force attacks harder.
*
* @return The delay time in milliseconds
*/
int getLoginFailureDelay();
/**
* The maximum number of time an anonymous user can fail to login before getting disconnected
* @return The maximum number of failer login attempts
*/
int getMaxAnonymousLogins();
/**
* The maximum number of concurrently logged in users
* @return The maximum number of users
*/
int getMaxLogins();
/**
* Is anonymous logins allowed at the server?
* @return true if anonymous logins are enabled
*/
boolean isAnonymousLoginEnabled();
/**
* Returns the maximum number of threads the server is allowed to create for
* processing client requests.
*
* @return the maximum number of threads the server is allowed to create for
* processing client requests.
*/
int getMaxThreads();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ConnectionConfig.java | Java | art | 2,262 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ssl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ssl.impl.DefaultSslConfiguration;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to configure the SSL settings for the control channel or the data
* channel.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SslConfigurationFactory {
private final Logger LOG = LoggerFactory
.getLogger(SslConfigurationFactory.class);
private File keystoreFile = new File("./res/.keystore");
private String keystorePass;
private String keystoreType = KeyStore.getDefaultType();
private String keystoreAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
private File trustStoreFile;
private String trustStorePass;
private String trustStoreType = KeyStore.getDefaultType();
private String trustStoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
private String sslProtocol = "TLS";
private ClientAuth clientAuth = ClientAuth.NONE;
private String keyPass;
private String keyAlias;
private String[] enabledCipherSuites;
/**
* The key store file used by this configuration
*
* @return The key store file
*/
public File getKeystoreFile() {
return keystoreFile;
}
/**
* Set the key store file to be used by this configuration
*
* @param keyStoreFile
* A path to an existing key store file
*/
public void setKeystoreFile(File keyStoreFile) {
this.keystoreFile = keyStoreFile;
}
/**
* The password used to load the key store
*
* @return The password
*/
public String getKeystorePassword() {
return keystorePass;
}
/**
* Set the password used to load the key store
*
* @param keystorePass
* The password
*/
public void setKeystorePassword(String keystorePass) {
this.keystorePass = keystorePass;
}
/**
* The key store type, defaults to @see {@link KeyStore#getDefaultType()}
*
* @return The key store type
*/
public String getKeystoreType() {
return keystoreType;
}
/**
* Set the key store type
*
* @param keystoreType
* The key store type
*/
public void setKeystoreType(String keystoreType) {
this.keystoreType = keystoreType;
}
/**
* The algorithm used to open the key store. Defaults to "SunX509"
*
* @return The key store algorithm
*/
public String getKeystoreAlgorithm() {
return keystoreAlgorithm;
}
/**
* Override the key store algorithm used to open the key store
*
* @param keystoreAlgorithm
* The key store algorithm
*/
public void setKeystoreAlgorithm(String keystoreAlgorithm) {
this.keystoreAlgorithm = keystoreAlgorithm;
}
/**
* The SSL protocol used for this channel. Supported values are "SSL" and
* "TLS". Defaults to "TLS".
*
* @return The SSL protocol
*/
public String getSslProtocol() {
return sslProtocol;
}
/**
* Set the SSL protocol used for this channel. Supported values are "SSL"
* and "TLS". Defaults to "TLS".
*
* @param sslProtocol
* The SSL protocol
*/
public void setSslProtocol(String sslProtocol) {
this.sslProtocol = sslProtocol;
}
/**
* Set what client authentication level to use, supported values are "yes"
* or "true" for required authentication, "want" for wanted authentication
* and "false" or "none" for no authentication. Defaults to "none".
*
* @param clientAuthReqd
* The desired authentication level
*/
public void setClientAuthentication(String clientAuthReqd) {
if ("true".equalsIgnoreCase(clientAuthReqd)
|| "yes".equalsIgnoreCase(clientAuthReqd)
|| "need".equalsIgnoreCase(clientAuthReqd)) {
this.clientAuth = ClientAuth.NEED;
} else if ("want".equalsIgnoreCase(clientAuthReqd)) {
this.clientAuth = ClientAuth.WANT;
} else {
this.clientAuth = ClientAuth.NONE;
}
}
/**
* The password used to load the key
*
* @return The password
*/
public String getKeyPassword() {
return keyPass;
}
/**
* Set the password used to load the key
*
* @param keyPass
* The password
*/
public void setKeyPassword(String keyPass) {
this.keyPass = keyPass;
}
/**
* Get the file used to load the truststore
* @return The {@link File} containing the truststore
*/
public File getTruststoreFile() {
return trustStoreFile;
}
/**
* Set the password used to load the trust store
*
* @param trustStoreFile
* The password
*/
public void setTruststoreFile(File trustStoreFile) {
this.trustStoreFile = trustStoreFile;
}
/**
* The password used to load the trust store
*
* @return The password
*/
public String getTruststorePassword() {
return trustStorePass;
}
/**
* Set the password used to load the trust store
*
* @param trustStorePass
* The password
*/
public void setTruststorePassword(String trustStorePass) {
this.trustStorePass = trustStorePass;
}
/**
* The trust store type, defaults to @see {@link KeyStore#getDefaultType()}
*
* @return The trust store type
*/
public String getTruststoreType() {
return trustStoreType;
}
/**
* Set the trust store type
*
* @param trustStoreType
* The trust store type
*/
public void setTruststoreType(String trustStoreType) {
this.trustStoreType = trustStoreType;
}
/**
* The algorithm used to open the trust store. Defaults to "SunX509"
*
* @return The trust store algorithm
*/
public String getTruststoreAlgorithm() {
return trustStoreAlgorithm;
}
/**
* Override the trust store algorithm used to open the trust store
*
* @param trustStoreAlgorithm
* The trust store algorithm
*/
public void setTruststoreAlgorithm(String trustStoreAlgorithm) {
this.trustStoreAlgorithm = trustStoreAlgorithm;
}
private KeyStore loadStore(File storeFile, String storeType,
String storePass) throws IOException, GeneralSecurityException {
InputStream fin = null;
try {
if(storeFile.exists()) {
LOG.debug("Trying to load store from file");
fin = new FileInputStream(storeFile);
} else {
LOG.debug("Trying to load store from classpath");
fin = getClass().getClassLoader().getResourceAsStream(storeFile.getPath());
if(fin == null) {
throw new FtpServerConfigurationException("Key store could not be loaded from " + storeFile.getPath());
}
}
KeyStore store = KeyStore.getInstance(storeType);
store.load(fin, storePass.toCharArray());
return store;
} finally {
IoUtils.close(fin);
}
}
/**
* Create an instance of {@link SslConfiguration} based on the configuration
* of this factory.
* @return The {@link SslConfiguration} instance
*/
public SslConfiguration createSslConfiguration() {
try {
// initialize keystore
LOG
.debug(
"Loading key store from \"{}\", using the key store type \"{}\"",
keystoreFile.getAbsolutePath(), keystoreType);
KeyStore keyStore = loadStore(keystoreFile, keystoreType,
keystorePass);
KeyStore trustStore;
if (trustStoreFile != null) {
LOG
.debug(
"Loading trust store from \"{}\", using the key store type \"{}\"",
trustStoreFile.getAbsolutePath(),
trustStoreType);
trustStore = loadStore(trustStoreFile, trustStoreType,
trustStorePass);
} else {
trustStore = keyStore;
}
String keyPassToUse;
if (keyPass == null) {
keyPassToUse = keystorePass;
} else {
keyPassToUse = keyPass;
}
// initialize key manager factory
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(keystoreAlgorithm);
keyManagerFactory.init(keyStore, keyPassToUse.toCharArray());
// initialize trust manager factory
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(trustStoreAlgorithm);
trustManagerFactory.init(trustStore);
return new DefaultSslConfiguration(
keyManagerFactory, trustManagerFactory,
clientAuth, sslProtocol,
enabledCipherSuites, keyAlias);
} catch (Exception ex) {
LOG.error("DefaultSsl.configure()", ex);
throw new FtpServerConfigurationException("DefaultSsl.configure()",
ex);
}
}
/**
* Return the required client authentication setting
*
* @return {@link ClientAuth#NEED} if client authentication is required,
* {@link ClientAuth#WANT} is client authentication is wanted or
* {@link ClientAuth#NONE} if no client authentication is the be
* performed
*/
public ClientAuth getClientAuth() {
return clientAuth;
}
/**
* Returns the cipher suites that should be enabled for this connection.
* Must return null if the default (as decided by the JVM) cipher suites
* should be used.
*
* @return An array of cipher suites, or null.
*/
public String[] getEnabledCipherSuites() {
if (enabledCipherSuites != null) {
return enabledCipherSuites.clone();
} else {
return null;
}
}
/**
* Set the allowed cipher suites, note that the exact list of supported
* cipher suites differs between JRE implementations.
*
* @param enabledCipherSuites
*/
public void setEnabledCipherSuites(String[] enabledCipherSuites) {
if (enabledCipherSuites != null) {
this.enabledCipherSuites = enabledCipherSuites.clone();
} else {
this.enabledCipherSuites = null;
}
}
/**
* Get the server key alias to be used for SSL communication
*
* @return The alias, or null if none is set
*/
public String getKeyAlias() {
return keyAlias;
}
/**
* Set the alias for the key to be used for SSL communication. If the
* specified key store contains multiple keys, this alias can be set to
* select a specific key.
*
* @param keyAlias
* The alias to use, or null if JSSE should be allowed to choose
* the key.
*/
public void setKeyAlias(String keyAlias) {
this.keyAlias = keyAlias;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/SslConfigurationFactory.java | Java | art | 12,798 |
/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.ssl;
/**
* Enumeration of possible levels of client authentication during an SSL
* session.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public enum ClientAuth {
/**
* Client authentication is required
*/
NEED,
/**
* Client authentication is requested but not required
*/
WANT,
/**
* Client authentication is not performed
*/
NONE
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/ClientAuth.java | Java | art | 1,067 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ssl.impl;
import java.security.GeneralSecurityException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.apache.ftpserver.ssl.ClientAuth;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.ftpserver.ssl.SslConfigurationFactory;
import org.apache.ftpserver.util.ClassUtils;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Used to configure the SSL settings for the control channel or the data
* channel.
*
* <strong><strong>Internal class, do not use directly.</strong></strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultSslConfiguration implements SslConfiguration {
private KeyManagerFactory keyManagerFactory;
private TrustManagerFactory trustManagerFactory;
private String sslProtocol = "TLS";
private ClientAuth clientAuth = ClientAuth.NONE;
private String keyAlias;
private String[] enabledCipherSuites;
/**
* Internal constructor, do not use directly. Instead, use {@link SslConfigurationFactory}
*/
public DefaultSslConfiguration(KeyManagerFactory keyManagerFactory,
TrustManagerFactory trustManagerFactory, ClientAuth clientAuthReqd,
String sslProtocol, String[] enabledCipherSuites, String keyAlias) {
super();
this.clientAuth = clientAuthReqd;
this.enabledCipherSuites = enabledCipherSuites;
this.keyAlias = keyAlias;
this.keyManagerFactory = keyManagerFactory;
this.sslProtocol = sslProtocol;
this.trustManagerFactory = trustManagerFactory;
}
/**
* @see SslConfiguration#getSSLContext(String)
*/
public SSLContext getSSLContext(String protocol)
throws GeneralSecurityException {
// null value check
if (protocol == null) {
protocol = sslProtocol;
}
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
// wrap key managers to allow us to control their behavior
// (FTPSERVER-93)
for (int i = 0; i < keyManagers.length; i++) {
if (ClassUtils.extendsClass(keyManagers[i].getClass(),
"javax.net.ssl.X509ExtendedKeyManager")) {
keyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i],
keyAlias);
} else if (keyManagers[i] instanceof X509KeyManager) {
keyManagers[i] = new AliasKeyManager(keyManagers[i], keyAlias);
}
}
// create SSLContext
// TODO revisit if we need caching of contexts.
SSLContext ctx = SSLContext.getInstance(protocol);
ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
return ctx;
}
/**
* @see SslConfiguration#getClientAuth()
*/
public ClientAuth getClientAuth() {
return clientAuth;
}
/**
* @see SslConfiguration#getSSLContext()
*/
public SSLContext getSSLContext() throws GeneralSecurityException {
return getSSLContext(sslProtocol);
}
/**
* @see SslConfiguration#getEnabledCipherSuites()
*/
public String[] getEnabledCipherSuites() {
if (enabledCipherSuites != null) {
return enabledCipherSuites.clone();
} else {
return null;
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/impl/DefaultSslConfiguration.java | Java | art | 4,315 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>SSL support implementation</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/impl/package.html | HTML | art | 977 |
/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.ssl.impl;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.X509KeyManager;
/**
* <strong>Internal class, do not use directly.</strong>
*
* X509KeyManager which allows selection of a specific keypair and certificate
* chain (identified by their keystore alias name) to be used by the server to
* authenticate itself to SSL clients.
*
* This class is only used on Java 1.4 systems, on Java 1.5 and newer the @see
* {@link ExtendedAliasKeyManager} is used instead
*
* Based of org.apache.tomcat.util.net.jsse.JSSEKeyManager.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public final class AliasKeyManager implements X509KeyManager {
private X509KeyManager delegate;
private String serverKeyAlias;
/**
* Constructor.
*
* @param mgr
* The X509KeyManager used as a delegate
* @param keyStore
* @param serverKeyAlias
* The alias name of the server's keypair and supporting
* certificate chain
* @param keyAlias
*/
public AliasKeyManager(KeyManager mgr, String keyAlias) {
this.delegate = (X509KeyManager) mgr;
this.serverKeyAlias = keyAlias;
}
/**
* Choose an alias to authenticate the client side of a secure socket, given
* the public key type and the list of certificate issuer authorities
* recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name(s), ordered with the
* most-preferred key type first
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use
*
* @return The alias name for the desired key, or null if there are no
* matches
*/
public String chooseClientAlias(String[] keyType, Principal[] issuers,
Socket socket) {
return delegate.chooseClientAlias(keyType, issuers, socket);
}
/**
* Returns this key manager's server key alias that was provided in the
* constructor.
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used (ignored)
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use (ignored)
*
* @return Alias name for the desired key
*/
public String chooseServerAlias(String keyType, Principal[] issuers,
Socket socket) {
if (serverKeyAlias != null) {
PrivateKey key = delegate.getPrivateKey(serverKeyAlias);
if (key != null) {
if (key.getAlgorithm().equals(keyType)) {
return serverKeyAlias;
} else {
return null;
}
} else {
return null;
}
} else {
return delegate.chooseServerAlias(keyType, issuers, socket);
}
}
/**
* Returns the certificate chain associated with the given alias.
*
* @param alias
* The alias name
*
* @return Certificate chain (ordered with the user's certificate first and
* the root certificate authority last), or null if the alias can't
* be found
*/
public X509Certificate[] getCertificateChain(String alias) {
return delegate.getCertificateChain(alias);
}
/**
* Get the matching aliases for authenticating the client side of a secure
* socket, given the public key type and the list of certificate issuer
* authorities recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
*
* @return Array of the matching alias names, or null if there were no
* matches
*/
public String[] getClientAliases(String keyType, Principal[] issuers) {
return delegate.getClientAliases(keyType, issuers);
}
/**
* Get the matching aliases for authenticating the server side of a secure
* socket, given the public key type and the list of certificate issuer
* authorities recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
*
* @return Array of the matching alias names, or null if there were no
* matches
*/
public String[] getServerAliases(String keyType, Principal[] issuers) {
return delegate.getServerAliases(keyType, issuers);
}
/**
* Returns the key associated with the given alias.
*
* @param alias
* The alias name
*
* @return The requested key, or null if the alias can't be found
*/
public PrivateKey getPrivateKey(String alias) {
return delegate.getPrivateKey(alias);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/impl/AliasKeyManager.java | Java | art | 6,421 |
/*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.ssl.impl;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
/**
* <strong>Internal class, do not use directly.</strong>
*
* X509KeyManager which allows selection of a specific keypair and certificate
* chain (identified by their keystore alias name) to be used by the server to
* authenticate itself to SSL clients.
*
* Based of org.apache.tomcat.util.net.jsse.JSSEKeyManager.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public final class ExtendedAliasKeyManager extends X509ExtendedKeyManager {
private X509ExtendedKeyManager delegate;
private String serverKeyAlias;
/**
* Constructor.
*
* @param mgr
* The X509KeyManager used as a delegate
* @param keyStore
* @param serverKeyAlias
* The alias name of the server's keypair and supporting
* certificate chain
* @param keyAlias
*/
public ExtendedAliasKeyManager(KeyManager mgr, String keyAlias) {
this.delegate = (X509ExtendedKeyManager) mgr;
this.serverKeyAlias = keyAlias;
}
/**
* Choose an alias to authenticate the client side of a secure socket, given
* the public key type and the list of certificate issuer authorities
* recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name(s), ordered with the
* most-preferred key type first
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use
*
* @return The alias name for the desired key, or null if there are no
* matches
*/
public String chooseClientAlias(String[] keyType, Principal[] issuers,
Socket socket) {
return delegate.chooseClientAlias(keyType, issuers, socket);
}
/**
* Returns this key manager's server key alias that was provided in the
* constructor if matching the key type.
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used (ignored)
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use (ignored)
*
* @return Alias name for the desired key
*/
public String chooseServerAlias(String keyType, Principal[] issuers,
Socket socket) {
if (serverKeyAlias != null) {
PrivateKey key = delegate.getPrivateKey(serverKeyAlias);
if (key != null) {
if (key.getAlgorithm().equals(keyType)) {
return serverKeyAlias;
} else {
return null;
}
} else {
return null;
}
} else {
return delegate.chooseServerAlias(keyType, issuers, socket);
}
}
/**
* Returns the certificate chain associated with the given alias.
*
* @param alias
* The alias name
*
* @return Certificate chain (ordered with the user's certificate first and
* the root certificate authority last), or null if the alias can't
* be found
*/
public X509Certificate[] getCertificateChain(String alias) {
return delegate.getCertificateChain(alias);
}
/**
* Get the matching aliases for authenticating the client side of a secure
* socket, given the public key type and the list of certificate issuer
* authorities recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
*
* @return Array of the matching alias names, or null if there were no
* matches
*/
public String[] getClientAliases(String keyType, Principal[] issuers) {
return delegate.getClientAliases(keyType, issuers);
}
/**
* Get the matching aliases for authenticating the server side of a secure
* socket, given the public key type and the list of certificate issuer
* authorities recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used
*
* @return Array of the matching alias names, or null if there were no
* matches
*/
public String[] getServerAliases(String keyType, Principal[] issuers) {
return delegate.getServerAliases(keyType, issuers);
}
/**
* Returns the key associated with the given alias.
*
* @param alias
* The alias name
*
* @return The requested key, or null if the alias can't be found
*/
public PrivateKey getPrivateKey(String alias) {
return delegate.getPrivateKey(alias);
}
/**
* Choose an alias to authenticate the client side of a secure socket, given
* the public key type and the list of certificate issuer authorities
* recognized by the peer (if any).
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used (ignored)
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use (ignored)
* @return The alias name for the desired key, or null if there are no
* matches
*/
public String chooseEngineClientAlias(String[] keyType,
Principal[] issuers, SSLEngine engine) {
return delegate.chooseEngineClientAlias(keyType, issuers, engine);
}
/**
* Returns this key manager's server key alias that was provided in the
* constructor if matching the key type.
*
* @param keyType
* The key algorithm type name
* @param issuers
* The list of acceptable CA issuer subject names, or null if it
* does not matter which issuers are used (ignored)
* @param socket
* The socket to be used for this connection. This parameter can
* be null, in which case this method will return the most
* generic alias to use (ignored)
*
* @return Alias name for the desired key
*/
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
SSLEngine engine) {
if (serverKeyAlias != null) {
PrivateKey key = delegate.getPrivateKey(serverKeyAlias);
if (key != null) {
if (key.getAlgorithm().equals(keyType)) {
return serverKeyAlias;
} else {
return null;
}
} else {
return null;
}
} else {
return delegate.chooseEngineServerAlias(keyType, issuers, engine);
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/impl/ExtendedAliasKeyManager.java | Java | art | 8,626 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.ssl;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
/**
* SSL configuration
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface SslConfiguration {
/**
* Return the SSL context for this configuration
*
* @return The {@link SSLContext}
* @throws GeneralSecurityException
*/
SSLContext getSSLContext() throws GeneralSecurityException;
/**
* Return the SSL context for this configuration given the specified
* protocol
*
* @param protocol
* The protocol, SSL or TLS must be supported
* @return The {@link SSLContext}
* @throws GeneralSecurityException
*/
SSLContext getSSLContext(String protocol) throws GeneralSecurityException;
/**
* Returns the cipher suites that should be enabled for this connection.
* Must return null if the default (as decided by the JVM) cipher suites
* should be used.
*
* @return An array of cipher suites, or null.
*/
String[] getEnabledCipherSuites();
/**
* Return the required client authentication setting
*
* @return {@link ClientAuth#NEED} if client authentication is required,
* {@link ClientAuth#WANT} is client authentication is wanted or
* {@link ClientAuth#NONE} if no client authentication is the be
* performed
*/
ClientAuth getClientAuth();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ssl/SslConfiguration.java | Java | art | 2,300 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command;
import java.io.IOException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* A command used primarily for overriding already installed commands when one
* wants to disable the command.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NotSupportedCommand extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// We do not support this command
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_502_COMMAND_NOT_IMPLEMENTED, "Not supported",
null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/NotSupportedCommand.java | Java | art | 1,858 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command;
import java.io.IOException;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
/**
* This interface encapsulates all the FTP commands.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface Command {
/**
* Execute command.
*
* @param session
* The current {@link FtpIoSession}
* @param context
* The current {@link FtpServerContext}
* @param request The current {@link FtpRequest}
* @throws IOException
* @throws FtpException
*/
void execute(FtpIoSession session, FtpServerContext context,
FtpRequest request) throws IOException, FtpException;
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/Command.java | Java | art | 1,674 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.ftpserver.command.impl.ABOR;
import org.apache.ftpserver.command.impl.ACCT;
import org.apache.ftpserver.command.impl.APPE;
import org.apache.ftpserver.command.impl.AUTH;
import org.apache.ftpserver.command.impl.CDUP;
import org.apache.ftpserver.command.impl.CWD;
import org.apache.ftpserver.command.impl.DELE;
import org.apache.ftpserver.command.impl.DefaultCommandFactory;
import org.apache.ftpserver.command.impl.EPRT;
import org.apache.ftpserver.command.impl.EPSV;
import org.apache.ftpserver.command.impl.FEAT;
import org.apache.ftpserver.command.impl.HELP;
import org.apache.ftpserver.command.impl.LANG;
import org.apache.ftpserver.command.impl.LIST;
import org.apache.ftpserver.command.impl.MD5;
import org.apache.ftpserver.command.impl.MDTM;
import org.apache.ftpserver.command.impl.MFMT;
import org.apache.ftpserver.command.impl.MKD;
import org.apache.ftpserver.command.impl.MLSD;
import org.apache.ftpserver.command.impl.MLST;
import org.apache.ftpserver.command.impl.MODE;
import org.apache.ftpserver.command.impl.NLST;
import org.apache.ftpserver.command.impl.NOOP;
import org.apache.ftpserver.command.impl.OPTS;
import org.apache.ftpserver.command.impl.PASS;
import org.apache.ftpserver.command.impl.PASV;
import org.apache.ftpserver.command.impl.PBSZ;
import org.apache.ftpserver.command.impl.PORT;
import org.apache.ftpserver.command.impl.PROT;
import org.apache.ftpserver.command.impl.PWD;
import org.apache.ftpserver.command.impl.QUIT;
import org.apache.ftpserver.command.impl.REIN;
import org.apache.ftpserver.command.impl.REST;
import org.apache.ftpserver.command.impl.RETR;
import org.apache.ftpserver.command.impl.RMD;
import org.apache.ftpserver.command.impl.RNFR;
import org.apache.ftpserver.command.impl.RNTO;
import org.apache.ftpserver.command.impl.SITE;
import org.apache.ftpserver.command.impl.SIZE;
import org.apache.ftpserver.command.impl.STAT;
import org.apache.ftpserver.command.impl.STOR;
import org.apache.ftpserver.command.impl.STOU;
import org.apache.ftpserver.command.impl.STRU;
import org.apache.ftpserver.command.impl.SYST;
import org.apache.ftpserver.command.impl.TYPE;
import org.apache.ftpserver.command.impl.USER;
/**
* Factory for {@link CommandFactory} instances
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class CommandFactoryFactory {
private static final HashMap<String, Command> DEFAULT_COMMAND_MAP = new HashMap<String, Command>();
static {
// first populate the default command list
DEFAULT_COMMAND_MAP.put("ABOR", new ABOR());
DEFAULT_COMMAND_MAP.put("ACCT", new ACCT());
DEFAULT_COMMAND_MAP.put("APPE", new APPE());
DEFAULT_COMMAND_MAP.put("AUTH", new AUTH());
DEFAULT_COMMAND_MAP.put("CDUP", new CDUP());
DEFAULT_COMMAND_MAP.put("CWD", new CWD());
DEFAULT_COMMAND_MAP.put("DELE", new DELE());
DEFAULT_COMMAND_MAP.put("EPRT", new EPRT());
DEFAULT_COMMAND_MAP.put("EPSV", new EPSV());
DEFAULT_COMMAND_MAP.put("FEAT", new FEAT());
DEFAULT_COMMAND_MAP.put("HELP", new HELP());
DEFAULT_COMMAND_MAP.put("LANG", new LANG());
DEFAULT_COMMAND_MAP.put("LIST", new LIST());
DEFAULT_COMMAND_MAP.put("MD5", new MD5());
DEFAULT_COMMAND_MAP.put("MFMT", new MFMT());
DEFAULT_COMMAND_MAP.put("MMD5", new MD5());
DEFAULT_COMMAND_MAP.put("MDTM", new MDTM());
DEFAULT_COMMAND_MAP.put("MLST", new MLST());
DEFAULT_COMMAND_MAP.put("MKD", new MKD());
DEFAULT_COMMAND_MAP.put("MLSD", new MLSD());
DEFAULT_COMMAND_MAP.put("MODE", new MODE());
DEFAULT_COMMAND_MAP.put("NLST", new NLST());
DEFAULT_COMMAND_MAP.put("NOOP", new NOOP());
DEFAULT_COMMAND_MAP.put("OPTS", new OPTS());
DEFAULT_COMMAND_MAP.put("PASS", new PASS());
DEFAULT_COMMAND_MAP.put("PASV", new PASV());
DEFAULT_COMMAND_MAP.put("PBSZ", new PBSZ());
DEFAULT_COMMAND_MAP.put("PORT", new PORT());
DEFAULT_COMMAND_MAP.put("PROT", new PROT());
DEFAULT_COMMAND_MAP.put("PWD", new PWD());
DEFAULT_COMMAND_MAP.put("QUIT", new QUIT());
DEFAULT_COMMAND_MAP.put("REIN", new REIN());
DEFAULT_COMMAND_MAP.put("REST", new REST());
DEFAULT_COMMAND_MAP.put("RETR", new RETR());
DEFAULT_COMMAND_MAP.put("RMD", new RMD());
DEFAULT_COMMAND_MAP.put("RNFR", new RNFR());
DEFAULT_COMMAND_MAP.put("RNTO", new RNTO());
DEFAULT_COMMAND_MAP.put("SITE", new SITE());
DEFAULT_COMMAND_MAP.put("SIZE", new SIZE());
DEFAULT_COMMAND_MAP.put("STAT", new STAT());
DEFAULT_COMMAND_MAP.put("STOR", new STOR());
DEFAULT_COMMAND_MAP.put("STOU", new STOU());
DEFAULT_COMMAND_MAP.put("STRU", new STRU());
DEFAULT_COMMAND_MAP.put("SYST", new SYST());
DEFAULT_COMMAND_MAP.put("TYPE", new TYPE());
DEFAULT_COMMAND_MAP.put("USER", new USER());
}
private Map<String, Command> commandMap = new HashMap<String, Command>();
private boolean useDefaultCommands = true;
/**
* Create an {@link CommandFactory} based on the configuration on the factory.
* @return The {@link CommandFactory}
*/
public CommandFactory createCommandFactory() {
Map<String, Command> mergedCommands = new HashMap<String, Command>();
if(useDefaultCommands) {
mergedCommands.putAll(DEFAULT_COMMAND_MAP);
}
mergedCommands.putAll(commandMap);
return new DefaultCommandFactory(mergedCommands);
}
/**
* Are default commands used?
*
* @return true if default commands are used
*/
public boolean isUseDefaultCommands() {
return useDefaultCommands;
}
/**
* Sets whether the default commands will be used.
*
* @param useDefaultCommands
* true if default commands should be used
*/
public void setUseDefaultCommands(final boolean useDefaultCommands) {
this.useDefaultCommands = useDefaultCommands;
}
/**
* Get the installed commands
*
* @return The installed commands
*/
public Map<String, Command> getCommandMap() {
return commandMap;
}
/**
* Add or override a command.
* @param commandName The command name, e.g. STOR
* @param command The command
*/
public void addCommand(String commandName, Command command) {
if(commandName == null) {
throw new NullPointerException("commandName can not be null");
}
if(command == null) {
throw new NullPointerException("command can not be null");
}
commandMap.put(commandName.toUpperCase(), command);
}
/**
* Set commands to add or override to the default commands
*
* @param commandMap
* The map of commands, the key will be used to map to requests.
*/
public void setCommandMap(final Map<String, Command> commandMap) {
if (commandMap == null) {
throw new NullPointerException("commandMap can not be null");
}
this.commandMap.clear();
for (Entry<String, Command> entry : commandMap.entrySet()) {
this.commandMap.put(entry.getKey().toUpperCase(), entry.getValue());
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/CommandFactoryFactory.java | Java | art | 8,279 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command;
/**
* Command factory interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface CommandFactory {
/**
* Get the command instance.
* @param commandName The name of the command to create
* @return The {@link Command} matching the provided name, or
* null if no such command exists.
*/
Command getCommand(String commandName);
/**
* Get the registered SITE commands
*
* @return Active site commands, the key is the site command name, used in
* FTP sessions as SITE <command name>
*/
// Map<String, Command> getSiteCommands();
/**
* Register SITE commands. The map can replace or append to the default SITE
* commands provided by FtpServer depending on the value of {@see
* CommandFactory#isUseDefaultSiteCommands()}
*
* @param siteCommands
* Active site commands, the key is the site command name, used
* in FTP sessions as SITE <command name>. The value is the
* command
*/
// void setSiteCommands(Map<String, Command> siteCommands);
/**
* Should custom site commands append to or replace the default commands
* provided by FtpServer?. The default is to append
*
* @return true if custom commands should append to the default, false if
* they should replace
*/
// boolean isUseDefaultSiteCommands();
/**
* Should custom site commands append to or replace the default commands
* provided by FtpServer?.
*
* @param useDefaultSiteCommands
* true if custom commands should append to the default, false if
* they should replace
*/
// void setUseDefaultSiteCommands(boolean useDefaultSiteCommands);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/CommandFactory.java | Java | art | 2,664 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>MDTM <SP> <pathname> <CRLF></code><br>
*
* Returns the date and time of when a file was modified.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MDTM extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MDTM.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MDTM", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MDTM",
fileName));
return;
}
// now print date
fileName = file.getAbsolutePath();
if (file.doesExist()) {
String dateStr = DateUtils.getFtpDate(file.getLastModified());
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_213_FILE_STATUS, "MDTM", dateStr));
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MDTM",
fileName));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MDTM.java | Java | art | 3,389 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Displays the FTP server timezone in RFC 822 format.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE_ZONE extends AbstractCommand {
private final static SimpleDateFormat TIMEZONE_FMT = new SimpleDateFormat(
"Z");
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// send timezone data
String timezone = TIMEZONE_FMT.format(new Date());
session.write(new DefaultFtpReply(FtpReply.REPLY_200_COMMAND_OKAY,
timezone));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE_ZONE.java | Java | art | 2,101 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.util.HashMap;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.command.Command;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>OPTS<SP> <command> <SP> <option> <CRLF></code><br>
*
* This command shall cause the server use optional features for the command
* specified.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class OPTS extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(OPTS.class);
private static final HashMap<String, Command> COMMAND_MAP = new HashMap<String, Command>(
16);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// no params
String argument = request.getArgument();
if (argument == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"OPTS", null));
return;
}
// get request name
int spaceIndex = argument.indexOf(' ');
if (spaceIndex != -1) {
argument = argument.substring(0, spaceIndex);
}
argument = argument.toUpperCase();
// call appropriate command method
String optsRequest = "OPTS_" + argument;
Command command = (Command) COMMAND_MAP.get(optsRequest);
try {
if (command != null) {
command.execute(session, context, request);
} else {
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_502_COMMAND_NOT_IMPLEMENTED,
"OPTS.not.implemented", argument));
}
} catch (Exception ex) {
LOG.warn("OPTS.execute()", ex);
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_500_SYNTAX_ERROR_COMMAND_UNRECOGNIZED,
"OPTS", null));
}
}
// initialize all the OPTS command handlers
static {
COMMAND_MAP.put("OPTS_MLST",
new org.apache.ftpserver.command.impl.OPTS_MLST());
COMMAND_MAP.put("OPTS_UTF8",
new org.apache.ftpserver.command.impl.OPTS_UTF8());
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/OPTS.java | Java | art | 3,859 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>STOR <SP> <pathname> <CRLF></code><br>
*
* This command causes the server-DTP to accept the data transferred via the
* data connection and to store the data as a file at the server site. If the
* file specified in the pathname exists at the server site, then its contents
* shall be replaced by the data being transferred. A new file is created at the
* server site if the file specified in the pathname does not already exist.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class STOR extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(STOR.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// get state variable
long skipLen = session.getFileOffset();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"STOR", null));
return;
}
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// get filename
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"STOR.invalid", fileName));
return;
}
fileName = file.getAbsolutePath();
// get permission
if (!file.isWritable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"STOR.permission", fileName));
return;
}
// get data connection
session.write(
LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "STOR",
fileName)).awaitUninterruptibly(10000);
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the input data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "STOR",
fileName));
return;
}
// transfer data
boolean failure = false;
OutputStream outStream = null;
try {
outStream = file.createOutputStream(skipLen);
long transSz = dataConnection.transferFromClient(session.getFtpletSession(), outStream);
// attempt to close the output stream so that errors in
// closing it will return an error to the client (FTPSERVER-119)
if(outStream != null) {
outStream.close();
}
LOG.info("File uploaded {}", fileName);
// notify the statistics component
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
ftpStat.setUpload(session, file, transSz);
} catch (SocketException ex) {
LOG.debug("Socket exception during data transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"STOR", fileName));
} catch (IOException ex) {
LOG.debug("IOException during data transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"STOR", fileName));
} finally {
// make sure we really close the output stream
IoUtils.close(outStream);
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "STOR",
fileName));
}
} finally {
session.resetState();
session.getDataConnection().closeDataConnection();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/STOR.java | Java | art | 8,070 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>RNTO <SP> <pathname> <CRLF></code><br>
*
* This command specifies the new pathname of the file specified in the
* immediately preceding "rename from" command. Together the two commands cause
* a file to be renamed.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RNTO extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(RNTO.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// argument check
String toFileStr = request.getArgument();
if (toFileStr == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"RNTO", null));
return;
}
// get the "rename from" file object
FtpFile frFile = session.getRenameFrom();
if (frFile == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS, "RNTO",
null));
return;
}
// get target file
FtpFile toFile = null;
try {
toFile = session.getFileSystemView().getFile(toFileStr);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (toFile == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_553_REQUESTED_ACTION_NOT_TAKEN_FILE_NAME_NOT_ALLOWED,
"RNTO.invalid", null));
return;
}
toFileStr = toFile.getAbsolutePath();
// check permission
if (!toFile.isWritable()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_553_REQUESTED_ACTION_NOT_TAKEN_FILE_NAME_NOT_ALLOWED,
"RNTO.permission", null));
return;
}
// check file existance
if (!frFile.doesExist()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_553_REQUESTED_ACTION_NOT_TAKEN_FILE_NAME_NOT_ALLOWED,
"RNTO.missing", null));
return;
}
// save away the old path
String logFrFileAbsolutePath = frFile.getAbsolutePath();
// now rename
if (frFile.move(toFile)) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "RNTO",
toFileStr));
LOG.info("File rename from \"{}\" to \"{}\"", logFrFileAbsolutePath,
toFile.getAbsolutePath());
} else {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_553_REQUESTED_ACTION_NOT_TAKEN_FILE_NAME_NOT_ALLOWED,
"RNTO", toFileStr));
}
} finally {
session.resetState();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/RNTO.java | Java | art | 6,003 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.usermanager.AnonymousAuthentication;
import org.apache.ftpserver.usermanager.UsernamePasswordAuthentication;
import org.apache.ftpserver.usermanager.impl.UserMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>PASS <SP> <password> <CRLF></code><br>
*
* The argument field is a Telnet string specifying the user's password. This
* command must be immediately preceded by the user name command.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PASS extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(PASS.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
boolean success = false;
ServerFtpStatistics stat = (ServerFtpStatistics) context
.getFtpStatistics();
try {
// reset state variables
session.resetState();
// argument check
String password = request.getArgument();
// check user name
String userName = session.getUserArgument();
if (userName == null && session.getUser() == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS, "PASS",
null));
return;
}
// already logged-in
if (session.isLoggedIn()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_202_COMMAND_NOT_IMPLEMENTED, "PASS",
null));
return;
}
// anonymous login limit check
boolean anonymous = userName != null
&& userName.equals("anonymous");
if (anonymous) {
int currAnonLogin = stat.getCurrentAnonymousLoginNumber();
int maxAnonLogin = context.getConnectionConfig()
.getMaxAnonymousLogins();
if(maxAnonLogin == 0) {
LOG.debug("Currently {} anonymous users logged in, unlimited allowed", currAnonLogin);
} else {
LOG.debug("Currently {} out of {} anonymous users logged in", currAnonLogin, maxAnonLogin);
}
if (currAnonLogin >= maxAnonLogin) {
LOG.debug("Too many anonymous users logged in, user will be disconnected");
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION,
"PASS.anonymous", null));
return;
}
}
// login limit check
int currLogin = stat.getCurrentLoginNumber();
int maxLogin = context.getConnectionConfig().getMaxLogins();
if(maxLogin == 0) {
LOG.debug("Currently {} users logged in, unlimited allowed", currLogin);
} else {
LOG.debug("Currently {} out of {} users logged in", currLogin, maxLogin);
}
if (maxLogin != 0 && currLogin >= maxLogin) {
LOG.debug("Too many users logged in, user will be disconnected");
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION,
"PASS.login", null));
return;
}
// authenticate user
UserManager userManager = context.getUserManager();
User authenticatedUser = null;
try {
UserMetadata userMetadata = new UserMetadata();
if (session.getRemoteAddress() instanceof InetSocketAddress) {
userMetadata.setInetAddress(((InetSocketAddress) session
.getRemoteAddress()).getAddress());
}
userMetadata.setCertificateChain(session
.getClientCertificates());
Authentication auth;
if (anonymous) {
auth = new AnonymousAuthentication(userMetadata);
} else {
auth = new UsernamePasswordAuthentication(userName,
password, userMetadata);
}
authenticatedUser = userManager.authenticate(auth);
} catch (AuthenticationFailedException e) {
authenticatedUser = null;
LOG.warn("User failed to log in");
} catch (Exception e) {
authenticatedUser = null;
LOG.warn("PASS.execute()", e);
}
// first save old values so that we can reset them if Ftplets
// tell us to fail
User oldUser = session.getUser();
String oldUserArgument = session.getUserArgument();
int oldMaxIdleTime = session.getMaxIdleTime();
if (authenticatedUser != null) {
if(!authenticatedUser.getEnabled()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_530_NOT_LOGGED_IN,
"PASS", null));
return;
}
session.setUser(authenticatedUser);
session.setUserArgument(null);
session.setMaxIdleTime(authenticatedUser.getMaxIdleTime());
success = true;
} else {
session.setUser(null);
}
if (!success) {
// reset due to failure
session.setUser(oldUser);
session.setUserArgument(oldUserArgument);
session.setMaxIdleTime(oldMaxIdleTime);
delayAfterLoginFailure(context.getConnectionConfig()
.getLoginFailureDelay());
LOG.warn("Login failure - " + userName);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_530_NOT_LOGGED_IN, "PASS", userName));
stat.setLoginFail(session);
session.increaseFailedLogins();
// kick the user if the max number of failed logins is reached
int maxAllowedLoginFailues = context.getConnectionConfig()
.getMaxLoginFailures();
if (maxAllowedLoginFailues != 0
&& session.getFailedLogins() >= maxAllowedLoginFailues) {
LOG.warn("User exceeded the number of allowed failed logins, session will be closed");
session.close(false).awaitUninterruptibly(10000);
}
return;
}
// update different objects
FileSystemFactory fmanager = context.getFileSystemManager();
FileSystemView fsview = fmanager
.createFileSystemView(authenticatedUser);
session.setLogin(fsview);
stat.setLogin(session);
// everything is fine - send login ok message
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_230_USER_LOGGED_IN, "PASS", userName));
if (anonymous) {
LOG.info("Anonymous login success - " + password);
} else {
LOG.info("Login success - " + userName);
}
} finally {
// if login failed - reset user
if (!success) {
session.reinitialize();
}
}
}
private void delayAfterLoginFailure(final int loginFailureDelay) {
if (loginFailureDelay > 0) {
LOG.debug("Waiting for " + loginFailureDelay
+ " milliseconds due to login failure");
try {
Thread.sleep(loginFailureDelay);
} catch (InterruptedException e) {
// ignore and go on
}
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PASS.java | Java | art | 10,750 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>MODE <SP> <mode-code> <CRLF></code><br>
*
* The argument is a single Telnet character code specifying the data transfer
* modes described in the Section on Transmission Modes.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MODE extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state
session.resetState();
// argument check
if (!request.hasArgument()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MODE", null));
return;
}
// set mode
char md = request.getArgument().charAt(0);
md = Character.toUpperCase(md);
if (md == 'S') {
session.getDataConnection().setZipMode(false);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "MODE", "S"));
} else if (md == 'Z') {
session.getDataConnection().setZipMode(true);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "MODE", "Z"));
} else {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"MODE", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MODE.java | Java | art | 3,114 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>SIZE <SP> <pathname> <CRLF></code><br>
*
* Returns the size of the file in bytes.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SIZE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(SIZE.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"SIZE", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"SIZE.missing", fileName));
return;
}
// print file size
fileName = file.getAbsolutePath();
if (!file.doesExist()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"SIZE.missing", fileName));
} else if (!file.isFile()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"SIZE.invalid", fileName));
} else {
String fileLen = String.valueOf(file.getSize());
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_213_FILE_STATUS, "SIZE", fileLen));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SIZE.java | Java | art | 3,577 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>CWD <SP> <pathname> <CRLF></code><br>
*
* This command allows the user to work with a different directory for file
* storage or retrieval without altering his login or accounting information.
* Transfer parameters are similarly unchanged. The argument is a pathname
* specifying a directory.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class CWD extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(CWD.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// get new directory name
String dirName = "/";
if (request.hasArgument()) {
dirName = request.getArgument();
}
// change directory
FileSystemView fsview = session.getFileSystemView();
boolean success = false;
try {
success = fsview.changeWorkingDirectory(dirName);
} catch (Exception ex) {
LOG.debug("Failed to change directory in file system", ex);
}
if (success) {
dirName = fsview.getWorkingDirectory().getAbsolutePath();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "CWD",
dirName));
} else {
session
.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"CWD", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/CWD.java | Java | art | 3,190 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.command.impl.listing.DirectoryLister;
import org.apache.ftpserver.command.impl.listing.LISTFileFormater;
import org.apache.ftpserver.command.impl.listing.ListArgument;
import org.apache.ftpserver.command.impl.listing.ListArgumentParser;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>LIST [<SP> <pathname>] <CRLF></code><br>
*
* This command causes a list to be sent from the server to the passive DTP. If
* the pathname specifies a directory or other group of files, the server should
* transfer a list of files in the specified directory. If the pathname
* specifies a file then the server should send current information on the file.
* A null argument implies the user's current working or default directory. The
* data transfer is over the data connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class LIST extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(LIST.class);
private static final LISTFileFormater LIST_FILE_FORMATER = new LISTFileFormater();
private DirectoryLister directoryLister = new DirectoryLister();
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// reset state variables
session.resetState();
// parse argument
ListArgument parsedArg = ListArgumentParser.parse(request
.getArgument());
// checl that the directory or file exists
FtpFile file = session.getFileSystemView().getFile(parsedArg.getFile());
if(!file.doesExist()) {
LOG.debug("Listing on a non-existing file");
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "LIST",
null));
return;
}
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "LIST", null));
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the output data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "LIST",
null));
return;
}
// transfer listing data
boolean failure = false;
try {
dataConnection.transferToClient(session.getFtpletSession(), directoryLister.listFiles(
parsedArg, session.getFileSystemView(),
LIST_FILE_FORMATER));
} catch (SocketException ex) {
LOG.debug("Socket exception during list transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"LIST", null));
} catch (IOException ex) {
LOG.debug("IOException during list transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"LIST", null));
} catch (IllegalArgumentException e) {
LOG.debug("Illegal list syntax: " + request.getArgument(), e);
// if listing syntax error - send message
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"LIST", null));
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "LIST",
null));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/LIST.java | Java | art | 7,365 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>QUIT <CRLF></code><br>
*
* This command terminates a USER and if file transfer is not in progress, the
* server closes the control connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class QUIT extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(QUIT.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_221_CLOSING_CONTROL_CONNECTION, "QUIT", null));
LOG.debug("QUIT received, closing session");
session.close(false).awaitUninterruptibly(10000);
session.getDataConnection().closeDataConnection();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/QUIT.java | Java | art | 2,214 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>RMD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname to be removed as
* a directory (if the pathname is absolute) or as a subdirectory of the current
* working directory (if the pathname is relative).
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RMD extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(RMD.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"RMD", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RMD.permission", fileName));
return;
}
fileName = file.getAbsolutePath();
// first let's make sure the path is a directory
if (!file.isDirectory()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RMD.invalid", fileName));
return;
}
// then make sure that the client did not request the deletion of
// current working directory.
FtpFile cwd = session.getFileSystemView().getWorkingDirectory();
if(file.equals(cwd)) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "RMD.busy",
fileName));
return;
}
// now check to see if the user have permission to delete this directory
if (!file.isRemovable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RMD.permission", fileName));
return;
}
// now delete directory
if (file.delete()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "RMD",
fileName));
// write log message
String userName = session.getUser().getName();
LOG.info("Directory remove : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
ftpStat.setRmdir(session, file);
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "RMD",
fileName));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/RMD.java | Java | art | 5,031 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.command.impl.listing.DirectoryLister;
import org.apache.ftpserver.command.impl.listing.FileFormater;
import org.apache.ftpserver.command.impl.listing.LISTFileFormater;
import org.apache.ftpserver.command.impl.listing.ListArgument;
import org.apache.ftpserver.command.impl.listing.ListArgumentParser;
import org.apache.ftpserver.command.impl.listing.NLSTFileFormater;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>NLST [<SP> <pathname>] <CRLF></code><br>
*
* This command causes a directory listing to be sent from server to user site.
* The pathname should specify a directory or other system-specific file group
* descriptor; a null argument implies the current directory. The server will
* return a stream of names of files and no other information.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NLST extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(NLST.class);
private static final NLSTFileFormater NLST_FILE_FORMATER = new NLSTFileFormater();
private static final LISTFileFormater LIST_FILE_FORMATER = new LISTFileFormater();
private DirectoryLister directoryLister = new DirectoryLister();
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// reset state
session.resetState();
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "NLST", null));
// print listing data
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the output data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "NLST",
null));
return;
}
boolean failure = false;
try {
// parse argument
ListArgument parsedArg = ListArgumentParser.parse(request
.getArgument());
FileFormater formater;
if (parsedArg.hasOption('l')) {
formater = LIST_FILE_FORMATER;
} else {
formater = NLST_FILE_FORMATER;
}
dataConnection.transferToClient(session.getFtpletSession(), directoryLister.listFiles(
parsedArg, session.getFileSystemView(), formater));
} catch (SocketException ex) {
LOG.debug("Socket exception during data transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"NLST", null));
} catch (IOException ex) {
LOG.debug("IOException during data transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"NLST", null));
} catch (IllegalArgumentException e) {
LOG
.debug("Illegal listing syntax: "
+ request.getArgument(), e);
// if listing syntax error - send message
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"LIST", null));
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "NLST",
null));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/NLST.java | Java | art | 7,139 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>FTP command implementations</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/package.html | HTML | art | 978 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.util.List;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.message.MessageResource;
/**
* <strong>Internal class, do not use directly.</strong>
*
* A new command "LANG" is added to the FTP command set to allow server-FTP
* process to determine in which language to present server greetings and the
* textual part of command responses.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class LANG extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// default language
String language = request.getArgument();
if (language == null) {
session.setLanguage(null);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "LANG", null));
return;
}
// check and set language
language = language.toLowerCase();
MessageResource msgResource = context.getMessageResource();
List<String> availableLanguages = msgResource.getAvailableLanguages();
if (availableLanguages != null) {
for (int i = 0; i < availableLanguages.size(); ++i) {
if (availableLanguages.get(i).equals(language)) {
session.setLanguage(language);
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_200_COMMAND_OKAY, "LANG",
null));
return;
}
}
}
// not found - send error message
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"LANG", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/LANG.java | Java | art | 3,225 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Show SITE help message.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE_HELP extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// print help message
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "SITE.HELP", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE_HELP.java | Java | art | 1,903 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>SYST <CRLF></code><br>
*
* This command is used to find out the type of operating system at the server.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SYST extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// get server system info
String systemName = System.getProperty("os.name");
if (systemName == null) {
systemName = "UNKNOWN";
} else {
systemName = systemName.toUpperCase();
systemName = systemName.replace(' ', '-');
}
// print server system info
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_215_NAME_SYSTEM_TYPE, "SYST", systemName));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SYST.java | Java | art | 2,236 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpStatistics;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.util.DateUtils;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Show all statistics information.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE_STAT extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// only administrator can execute this
UserManager userManager = context.getUserManager();
boolean isAdmin = userManager.isAdmin(session.getUser().getName());
if (!isAdmin) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_530_NOT_LOGGED_IN, "SITE", null));
return;
}
// get statistics information
FtpStatistics stat = context.getFtpStatistics();
StringBuffer sb = new StringBuffer(256);
sb.append('\n');
sb.append("Start Time : ").append(
DateUtils.getISO8601Date(stat.getStartTime().getTime()))
.append('\n');
sb.append("File Upload Number : ").append(
stat.getTotalUploadNumber()).append('\n');
sb.append("File Download Number : ").append(
stat.getTotalDownloadNumber()).append('\n');
sb.append("File Delete Number : ").append(
stat.getTotalDeleteNumber()).append('\n');
sb.append("File Upload Bytes : ").append(
stat.getTotalUploadSize()).append('\n');
sb.append("File Download Bytes : ").append(
stat.getTotalDownloadSize()).append('\n');
sb.append("Directory Create Number : ").append(
stat.getTotalDirectoryCreated()).append('\n');
sb.append("Directory Remove Number : ").append(
stat.getTotalDirectoryRemoved()).append('\n');
sb.append("Current Logins : ").append(
stat.getCurrentLoginNumber()).append('\n');
sb.append("Total Logins : ").append(
stat.getTotalLoginNumber()).append('\n');
sb.append("Current Anonymous Logins : ").append(
stat.getCurrentAnonymousLoginNumber()).append('\n');
sb.append("Total Anonymous Logins : ").append(
stat.getTotalAnonymousLoginNumber()).append('\n');
sb.append("Current Connections : ").append(
stat.getCurrentConnectionNumber()).append('\n');
sb.append("Total Connections : ").append(
stat.getTotalConnectionNumber()).append('\n');
sb.append('\n');
session.write(new DefaultFtpReply(FtpReply.REPLY_200_COMMAND_OKAY, sb
.toString()));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE_STAT.java | Java | art | 4,326 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DataType;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>RETR <SP> <pathname> <CRLF></code><br>
*
* This command causes the server-DTP to transfer a copy of the file, specified
* in the pathname, to the server- or user-DTP at the other end of the data
* connection. The status and contents of the file at the server site shall be
* unaffected.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RETR extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(RETR.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// get state variable
long skipLen = session.getFileOffset();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"RETR", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RETR.missing", fileName));
return;
}
fileName = file.getAbsolutePath();
// check file existance
if (!file.doesExist()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RETR.missing", fileName));
return;
}
// check valid file
if (!file.isFile()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RETR.invalid", fileName));
return;
}
// check permission
if (!file.isReadable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"RETR.permission", fileName));
return;
}
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "RETR", null));
// send file data to client
boolean failure = false;
InputStream is = null;
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the output data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "RETR",
null));
return;
}
try {
// open streams
is = openInputStream(session, file, skipLen);
// transfer data
long transSz = dataConnection.transferToClient(session.getFtpletSession(), is);
// attempt to close the input stream so that errors in
// closing it will return an error to the client (FTPSERVER-119)
if(is != null) {
is.close();
}
LOG.info("File downloaded {}", fileName);
// notify the statistics component
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
if (ftpStat != null) {
ftpStat.setDownload(session, file, transSz);
}
} catch (SocketException ex) {
LOG.debug("Socket exception during data transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"RETR", fileName));
} catch (IOException ex) {
LOG.debug("IOException during data transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"RETR", fileName));
} finally {
// make sure we really close the input stream
IoUtils.close(is);
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "RETR",
fileName));
}
} finally {
session.resetState();
session.getDataConnection().closeDataConnection();
}
}
/**
* Skip length and open input stream.
*/
public InputStream openInputStream(FtpIoSession session, FtpFile file,
long skipLen) throws IOException {
InputStream in;
if (session.getDataType() == DataType.ASCII) {
int c;
long offset = 0L;
in = new BufferedInputStream(file.createInputStream(0L));
while (offset++ < skipLen) {
if ((c = in.read()) == -1) {
throw new IOException("Cannot skip");
}
if (c == '\n') {
offset++;
}
}
} else {
in = file.createInputStream(skipLen);
}
return in;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/RETR.java | Java | art | 9,396 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>CDUP <CRLF></code><br>
*
* This command is a special case of CWD, and is included to simplify the
* implementation of programs for transferring directory trees between operating
* systems having different syntaxes for naming the parent directory. The reply
* codes shall be identical to the reply codes of CWD.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class CDUP extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(CDUP.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// change directory
FileSystemView fsview = session.getFileSystemView();
boolean success = false;
try {
success = fsview.changeWorkingDirectory("..");
} catch (Exception ex) {
LOG.debug("Failed to change directory in file system", ex);
}
if (success) {
String dirName = fsview.getWorkingDirectory().getAbsolutePath();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "CDUP",
dirName));
} else {
session.write(LocalizedFtpReply
.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"CDUP", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/CDUP.java | Java | art | 3,048 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>MD5 <SP> <pathname> <CRLF></code><br>
* <code>MMD5 <SP> <pathnames> <CRLF></code><br>
*
* Returns the MD5 value for a file or multiple files according to
* draft-twine-ftpmd5-00.txt.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MD5 extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MD5.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
boolean isMMD5 = false;
if ("MMD5".equals(request.getCommand())) {
isMMD5 = true;
}
// print file information
String argument = request.getArgument();
if (argument == null || argument.trim().length() == 0) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"MD5.invalid", null));
return;
}
String[] fileNames = null;
if (isMMD5) {
fileNames = argument.split(",");
} else {
fileNames = new String[] { argument };
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < fileNames.length; i++) {
String fileName = fileNames[i].trim();
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting the file object: " + fileName, ex);
}
if (file == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"MD5.invalid", fileName));
return;
}
// check file
if (!file.isFile()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"MD5.invalid", fileName));
return;
}
InputStream is = null;
try {
is = file.createInputStream(0);
String md5Hash = md5(is);
if (i > 0) {
sb.append(", ");
}
boolean nameHasSpaces = fileName.indexOf(' ') >= 0;
if(nameHasSpaces) {
sb.append('"');
}
sb.append(fileName);
if(nameHasSpaces) {
sb.append('"');
}
sb.append(' ');
sb.append(md5Hash);
} catch (NoSuchAlgorithmException e) {
LOG.debug("MD5 algorithm not available", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_502_COMMAND_NOT_IMPLEMENTED,
"MD5.notimplemened", null));
} finally {
IoUtils.close(is);
}
}
if (isMMD5) {
session.write(LocalizedFtpReply.translate(session, request, context,
252, "MMD5", sb.toString()));
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
251, "MD5", sb.toString()));
}
}
/**
* @param is
* InputStream for which the MD5 hash is calculated
* @return The hash of the content in the input stream
* @throws IOException
* @throws NoSuchAlgorithmException
*/
private String md5(InputStream is) throws IOException,
NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
DigestInputStream dis = new DigestInputStream(is, digest);
byte[] buffer = new byte[1024];
int read = dis.read(buffer);
while (read > -1) {
read = dis.read(buffer);
}
return new String(encodeHex(dis.getMessageDigest().digest()));
}
/**
* Converts an array of bytes into an array of characters representing the
* hexidecimal values of each byte in order. The returned array will be
* double the length of the passed array, as it takes two characters to
* represent any given byte.
*
* @param data
* a byte[] to convert to Hex characters
* @return A char[] containing hexidecimal characters
*/
public static char[] encodeHex(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS[0x0F & data[i]];
}
return out;
}
/**
* Used to build output as Hex
*/
private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MD5.java | Java | art | 7,520 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>REIN <CRLF></code><br>
*
* This command flushes a USER, without affecting transfers in progress. The
* server state should otherwise be as when the user first connects.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class REIN extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
session.reinitialize();
session.setLanguage(null);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_220_SERVICE_READY, "REIN", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/REIN.java | Java | art | 1,964 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.security.GeneralSecurityException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.ssl.ClientAuth;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.filter.ssl.SslFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This server supports explicit SSL support.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class AUTH extends AbstractCommand {
private static final String SSL_SESSION_FILTER_NAME = "sslSessionFilter";
private final Logger LOG = LoggerFactory.getLogger(AUTH.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// argument check
if (!request.hasArgument()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"AUTH", null));
return;
}
// check SSL configuration
if (session.getListener().getSslConfiguration() == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
431, "AUTH", null));
return;
}
// check that we don't already have a SSL filter in place due to running
// in implicit mode
// or because the AUTH command has already been issued. This is what the
// RFC says:
// "Some servers will allow the AUTH command to be reissued in order
// to establish new authentication. The AUTH command, if accepted,
// removes any state associated with prior FTP Security commands.
// The server must also require that the user reauthorize (that is,
// reissue some or all of the USER, PASS, and ACCT commands) in this
// case (see section 4 for an explanation of "authorize" in this
// context)."
// Here we choose not to support reissued AUTH
if (session.getFilterChain().contains(SslFilter.class)) {
session.write(LocalizedFtpReply.translate(session, request, context,
534, "AUTH", null));
return;
}
// check parameter
String authType = request.getArgument().toUpperCase();
if (authType.equals("SSL")) {
try {
secureSession(session, "SSL");
session.write(LocalizedFtpReply.translate(session, request, context,
234, "AUTH.SSL", null));
} catch (FtpException ex) {
throw ex;
} catch (Exception ex) {
LOG.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
} else if (authType.equals("TLS")) {
try {
secureSession(session, "TLS");
session.write(LocalizedFtpReply.translate(session, request, context,
234, "AUTH.TLS", null));
} catch (FtpException ex) {
throw ex;
} catch (Exception ex) {
LOG.warn("AUTH.execute()", ex);
throw new FtpException("AUTH.execute()", ex);
}
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_502_COMMAND_NOT_IMPLEMENTED, "AUTH", null));
}
}
private void secureSession(final FtpIoSession session, final String type)
throws GeneralSecurityException, FtpException {
SslConfiguration ssl = session.getListener().getSslConfiguration();
if (ssl != null) {
session.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE);
SslFilter sslFilter = new SslFilter(ssl.getSSLContext());
if (ssl.getClientAuth() == ClientAuth.NEED) {
sslFilter.setNeedClientAuth(true);
} else if (ssl.getClientAuth() == ClientAuth.WANT) {
sslFilter.setWantClientAuth(true);
}
// note that we do not care about the protocol, we allow both types
// and leave it to the SSL handshake to determine the protocol to
// use. Thus the type argument is ignored.
if (ssl.getEnabledCipherSuites() != null) {
sslFilter.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
}
session.getFilterChain().addFirst(SSL_SESSION_FILTER_NAME,
sslFilter);
} else {
throw new FtpException("Socket factory SSL not configured");
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/AUTH.java | Java | art | 6,049 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.util.IllegalInetAddressException;
import org.apache.ftpserver.util.IllegalPortException;
import org.apache.ftpserver.util.SocketAddressEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>PORT <SP> <host-port> <CRLF></code><br>
*
* The argument is a HOST-PORT specification for the data port to be used in
* data connection. There are defaults for both the user and server data ports,
* and under normal circumstances this command and its reply are not needed. If
* this command is used, the argument is the concatenation of a 32-bit internet
* host address and a 16-bit TCP port address. This address information is
* broken into 8-bit fields and the value of each field is transmitted as a
* decimal number (in character string representation). The fields are separated
* by commas. A port command would be:
*
* PORT h1,h2,h3,h4,p1,p2
*
* where h1 is the high order 8 bits of the internet host address.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PORT extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(PORT.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// argument check
if (!request.hasArgument()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"PORT", null));
return;
}
// is port enabled
DataConnectionConfiguration dataCfg = session.getListener()
.getDataConnectionConfiguration();
if (!dataCfg.isActiveEnabled()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "PORT.disabled", null));
return;
}
InetSocketAddress address;
try {
address = SocketAddressEncoder.decode(request.getArgument());
// port must not be 0
if(address.getPort() == 0) {
throw new IllegalPortException("PORT port must not be 0");
}
} catch (IllegalInetAddressException e) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "PORT", null));
return;
} catch (IllegalPortException e) {
LOG.debug("Invalid data port: " + request.getArgument(), e);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"PORT.invalid", null));
return;
} catch (UnknownHostException e) {
LOG.debug("Unknown host", e);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"PORT.host", null));
return;
}
// check IP
if (dataCfg.isActiveIpCheck()) {
if (session.getRemoteAddress() instanceof InetSocketAddress) {
InetAddress clientAddr = ((InetSocketAddress) session
.getRemoteAddress()).getAddress();
if (!address.getAddress().equals(clientAddr)) {
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "PORT.mismatch", null));
return;
}
}
}
session.getDataConnection().initActiveDataConnection(address);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "PORT", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PORT.java | Java | art | 5,928 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>ABOR <CRLF></code><br>
*
* This command tells the server to abort the previous FTP service command and
* any associated transfer of data. No action is to be taken if the previous
* command has been completed (including data transfer). The control connection
* is not to be closed by the server, but the data connection must be closed.
* Current implementation does not do anything. As here data transfers are not
* multi-threaded.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ABOR extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// and abort any data connection
session.getDataConnection().closeDataConnection();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "ABOR", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/ABOR.java | Java | art | 2,337 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.ftpserver.command.Command;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.command.CommandFactoryFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Command factory to return appropriate command implementation depending on the
* FTP request command string.
*
* <strong><strong>Internal class, do not use directly.</strong></strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultCommandFactory implements CommandFactory {
/**
* Internal constructor, use {@link CommandFactoryFactory} instead
*/
public DefaultCommandFactory(Map<String, Command> commandMap) {
this.commandMap = commandMap;
}
private Map<String, Command> commandMap = new HashMap<String, Command>();
/**
* Get command. Returns null if not found.
*/
public Command getCommand(final String cmdName) {
if (cmdName == null || cmdName.equals("")) {
return null;
}
String upperCaseCmdName = cmdName.toUpperCase();
return commandMap.get(upperCaseCmdName);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/DefaultCommandFactory.java | Java | art | 2,050 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>STOU <CRLF></code><br>
*
* This command behaves like STOR except that the resultant file is to be
* created in the current directory under a name unique to that directory. The
* 150 Transfer Started response must include the name generated, See RFC1123
* section 4.1.2.9
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class STOU extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(STOU.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// reset state variables
session.resetState();
String pathName = request.getArgument();
// get filenames
FtpFile file = null;
try {
String filePrefix;
if (pathName == null) {
filePrefix = "ftp.dat";
} else {
FtpFile dir = session.getFileSystemView().getFile(
pathName);
if (dir.isDirectory()) {
filePrefix = pathName + "/ftp.dat";
} else {
filePrefix = pathName;
}
}
file = session.getFileSystemView().getFile(filePrefix);
if (file != null) {
file = getUniqueFile(session, file);
}
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "STOU",
null));
return;
}
String fileName = file.getAbsolutePath();
// check permission
if (!file.isWritable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"STOU.permission", fileName));
return;
}
// get data connection
session.write(new DefaultFtpReply(
FtpReply.REPLY_150_FILE_STATUS_OKAY, "FILE: " + fileName));
// get data from client
boolean failure = false;
OutputStream os = null;
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the input data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "STOU",
fileName));
return;
}
try {
// open streams
os = file.createOutputStream(0L);
// transfer data
long transSz = dataConnection.transferFromClient(session.getFtpletSession(), os);
// attempt to close the output stream so that errors in
// closing it will return an error to the client (FTPSERVER-119)
if(os != null) {
os.close();
}
LOG.info("File uploaded {}", fileName);
// notify the statistics component
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
if (ftpStat != null) {
ftpStat.setUpload(session, file, transSz);
}
} catch (SocketException ex) {
LOG.debug("Socket exception during data transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"STOU", fileName));
} catch (IOException ex) {
LOG.debug("IOException during data transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"STOU", fileName));
} finally {
// make sure we really close the output stream
IoUtils.close(os);
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "STOU",
fileName));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
/**
* Get unique file object.
*/
protected FtpFile getUniqueFile(FtpIoSession session, FtpFile oldFile)
throws FtpException {
FtpFile newFile = oldFile;
FileSystemView fsView = session.getFileSystemView();
String fileName = newFile.getAbsolutePath();
while (newFile.doesExist()) {
newFile = fsView.getFile(fileName + '.'
+ System.currentTimeMillis());
if (newFile == null) {
break;
}
}
return newFile;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/STOU.java | Java | art | 8,499 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Selects files that are visible
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class VisibleFileFilter implements FileFilter {
private FileFilter wrappedFilter;
/**
* Default constructor
*/
public VisibleFileFilter() {
// default cstr
}
/**
* Constructor with a wrapped filter, allows for chaining filters
*
* @param wrappedFilter
* The {@link FileFilter} to wrap
*/
public VisibleFileFilter(FileFilter wrappedFilter) {
this.wrappedFilter = wrappedFilter;
}
/**
* @see FileFilter#accept(FtpFile)
*/
public boolean accept(FtpFile file) {
if (wrappedFilter != null && !wrappedFilter.accept(file)) {
return false;
}
return !file.isHidden();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/VisibleFileFilter.java | Java | art | 1,802 |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>File listing implementations used by various FTP commands</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/package.html | HTML | art | 1,008 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Formats files according to the NLST specification
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NLSTFileFormater implements FileFormater {
private final static char[] NEWLINE = { '\r', '\n' };
/**
* @see FileFormater#format(FtpFile)
*/
public String format(FtpFile file) {
StringBuffer sb = new StringBuffer();
sb.append(file.getName());
sb.append(NEWLINE);
return sb.toString();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/NLSTFileFormater.java | Java | art | 1,459 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.util.DateUtils;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Formats files according to the MLST specification
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MLSTFileFormater implements FileFormater {
private static final String[] DEFAULT_TYPES = new String[] { "Size",
"Modify", "Type" };
private final static char[] NEWLINE = { '\r', '\n' };
private String[] selectedTypes = DEFAULT_TYPES;
/**
* @param selectedTypes
* The types to show in the formated file
*/
public MLSTFileFormater(String[] selectedTypes) {
if (selectedTypes != null) {
this.selectedTypes = selectedTypes.clone();
}
}
/**
* @see FileFormater#format(FtpFile)
*/
public String format(FtpFile file) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < selectedTypes.length; ++i) {
String type = selectedTypes[i];
if (type.equalsIgnoreCase("size")) {
sb.append("Size=");
sb.append(String.valueOf(file.getSize()));
sb.append(';');
} else if (type.equalsIgnoreCase("modify")) {
String timeStr = DateUtils.getFtpDate(file.getLastModified());
sb.append("Modify=");
sb.append(timeStr);
sb.append(';');
} else if (type.equalsIgnoreCase("type")) {
if (file.isFile()) {
sb.append("Type=file;");
} else if (file.isDirectory()) {
sb.append("Type=dir;");
}
} else if (type.equalsIgnoreCase("perm")) {
sb.append("Perm=");
if (file.isReadable()) {
if (file.isFile()) {
sb.append('r');
} else if (file.isDirectory()) {
sb.append('e');
sb.append('l');
}
}
if (file.isWritable()) {
if (file.isFile()) {
sb.append('a');
sb.append('d');
sb.append('f');
sb.append('w');
} else if (file.isDirectory()) {
sb.append('f');
sb.append('p');
sb.append('c');
sb.append('m');
}
}
sb.append(';');
}
}
sb.append(' ');
sb.append(file.getName());
sb.append(NEWLINE);
return sb.toString();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/MLSTFileFormater.java | Java | art | 3,660 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Contains the parsed argument for a list command (e.g. LIST or NLST)
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ListArgument {
private String file;
private String pattern;
private char[] options;
/**
* @param file
* The file path including the directory
* @param pattern
* A regular expression pattern that files must match
* @param options
* List options, such as -la
*/
public ListArgument(String file, String pattern, char[] options) {
this.file = file;
this.pattern = pattern;
if (options == null) {
this.options = new char[0];
} else {
this.options = options.clone();
}
}
/**
* The listing options,
*
* @return All options
*/
public char[] getOptions() {
return options.clone();
}
/**
* The regular expression pattern that files must match
*
* @return The regular expression
*/
public String getPattern() {
return pattern;
}
/**
* Checks if a certain option is set
*
* @param option
* The option to check
* @return true if the option is set
*/
public boolean hasOption(char option) {
for (int i = 0; i < options.length; i++) {
if (option == options[i]) {
return true;
}
}
return false;
}
/**
* The file path including the directory
*
* @return The file path
*/
public String getFile() {
return file;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/ListArgument.java | Java | art | 2,587 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.util.RegularExpr;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Selects files which short name matches a regular expression
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RegexFileFilter implements FileFilter {
private RegularExpr regex;
private FileFilter wrappedFilter;
/**
* Constructor with a regular expression
*
* @param regex
* The regular expression to select by
*/
public RegexFileFilter(String regex) {
this.regex = new RegularExpr(regex);
}
/**
* Constructor with a wrapped filter, allows for chaining filters
*
* @param regex
* The regular expression to select by
* @param wrappedFilter
* The {@link FileFilter} to wrap
*/
public RegexFileFilter(String regex, FileFilter wrappedFilter) {
this(regex);
this.wrappedFilter = wrappedFilter;
}
/**
* @see FileFilter#accept(FtpFile)
*/
public boolean accept(FtpFile file) {
if (wrappedFilter != null && !wrappedFilter.accept(file)) {
return false;
}
return regex.isMatch(file.getName());
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/RegexFileFilter.java | Java | art | 2,160 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import java.util.StringTokenizer;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Parses a list argument (e.g. for LIST or NLST) into a {@link ListArgument}
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ListArgumentParser {
/**
* Parse the argument
*
* @param argument
* The argument string
* @return The parsed argument
* @throws IllegalArgumentException
* If the argument string is incorrectly formated
*/
public static ListArgument parse(String argument) {
String file = "./";
String options = "";
String pattern = "*";
// find options and file name (may have regular expression)
if (argument != null) {
argument = argument.trim();
StringBuffer optionsSb = new StringBuffer(4);
StringBuffer fileSb = new StringBuffer(16);
StringTokenizer st = new StringTokenizer(argument, " ", true);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (fileSb.length() != 0) {
// file name started - append to file name buffer
fileSb.append(token);
} else if (token.equals(" ")) {
// delimiter and file not started - ignore
continue;
} else if (token.charAt(0) == '-') {
// token and file name not started - append to options
// buffer
if (token.length() > 1) {
optionsSb.append(token.substring(1));
}
} else {
// filename - append to the filename buffer
fileSb.append(token);
}
}
if (fileSb.length() != 0) {
file = fileSb.toString();
}
options = optionsSb.toString();
}
int slashIndex = file.lastIndexOf('/');
if (slashIndex == -1) {
if (containsPattern(file)) {
pattern = file;
file = "./";
}
} else if (slashIndex != (file.length() - 1)) {
String after = file.substring(slashIndex + 1);
if (containsPattern(after)) {
pattern = file.substring(slashIndex + 1);
file = file.substring(0, slashIndex + 1);
}
if (containsPattern(file)) {
throw new IllegalArgumentException(
"Directory path can not contain regular expression");
}
}
if ("*".equals(pattern) || "".equals(pattern)) {
pattern = null;
}
return new ListArgument(file, pattern, options.toCharArray());
}
private static boolean containsPattern(String file) {
return file.indexOf('*') > -1 || file.indexOf('?') > -1
|| file.indexOf('[') > -1;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/ListArgumentParser.java | Java | art | 3,890 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Interface for formating output based on a {@link FtpFile}
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileFormater {
/**
* Format the file
*
* @param file
* The {@link FtpFile}
* @return The formated string based on the {@link FtpFile}
*/
String format(FtpFile file);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/FileFormater.java | Java | art | 1,342 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This class prints file listing.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DirectoryLister {
private String traverseFiles(final List<FtpFile> files,
final FileFilter filter, final FileFormater formater) {
StringBuffer sb = new StringBuffer();
sb.append(traverseFiles(files, filter, formater, true));
sb.append(traverseFiles(files, filter, formater, false));
return sb.toString();
}
private String traverseFiles(final List<FtpFile> files,
final FileFilter filter, final FileFormater formater,
boolean matchDirs) {
StringBuffer sb = new StringBuffer();
for (FtpFile file : files) {
if (file == null) {
continue;
}
if (filter == null || filter.accept(file)) {
if (file.isDirectory() == matchDirs) {
sb.append(formater.format(file));
}
}
}
return sb.toString();
}
public String listFiles(final ListArgument argument,
final FileSystemView fileSystemView, final FileFormater formater)
throws IOException {
StringBuffer sb = new StringBuffer();
// get all the file objects
List<FtpFile> files = listFiles(fileSystemView, argument.getFile());
if (files != null) {
FileFilter filter = null;
if (!argument.hasOption('a')) {
filter = new VisibleFileFilter();
}
if (argument.getPattern() != null) {
filter = new RegexFileFilter(argument.getPattern(), filter);
}
sb.append(traverseFiles(files, filter, formater));
}
return sb.toString();
}
/**
* Get the file list. Files will be listed in alphabetlical order.
*/
private List<FtpFile> listFiles(FileSystemView fileSystemView, String file) {
List<FtpFile> files = null;
try {
FtpFile virtualFile = fileSystemView.getFile(file);
if (virtualFile.isFile()) {
files = new ArrayList<FtpFile>();
files.add(virtualFile);
} else {
files = virtualFile.listFiles();
}
} catch (FtpException ex) {
}
return files;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/DirectoryLister.java | Java | art | 3,526 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import java.util.Arrays;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.util.DateUtils;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Formats files according to the LIST specification
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class LISTFileFormater implements FileFormater {
private final static char DELIM = ' ';
private final static char[] NEWLINE = { '\r', '\n' };
/**
* @see FileFormater#format(FtpFile)
*/
public String format(FtpFile file) {
StringBuffer sb = new StringBuffer();
sb.append(getPermission(file));
sb.append(DELIM);
sb.append(DELIM);
sb.append(DELIM);
sb.append(String.valueOf(file.getLinkCount()));
sb.append(DELIM);
sb.append(file.getOwnerName());
sb.append(DELIM);
sb.append(file.getGroupName());
sb.append(DELIM);
sb.append(getLength(file));
sb.append(DELIM);
sb.append(getLastModified(file));
sb.append(DELIM);
sb.append(file.getName());
sb.append(NEWLINE);
return sb.toString();
}
/**
* Get size
*/
private String getLength(FtpFile file) {
String initStr = " ";
long sz = 0;
if (file.isFile()) {
sz = file.getSize();
}
String szStr = String.valueOf(sz);
if (szStr.length() > initStr.length()) {
return szStr;
}
return initStr.substring(0, initStr.length() - szStr.length()) + szStr;
}
/**
* Get last modified date string.
*/
private String getLastModified(FtpFile file) {
return DateUtils.getUnixDate(file.getLastModified());
}
/**
* Get permission string.
*/
private char[] getPermission(FtpFile file) {
char permission[] = new char[10];
Arrays.fill(permission, '-');
permission[0] = file.isDirectory() ? 'd' : '-';
permission[1] = file.isReadable() ? 'r' : '-';
permission[2] = file.isWritable() ? 'w' : '-';
permission[3] = file.isDirectory() ? 'x' : '-';
return permission;
}
/*
* public String format(FileObject[] files) { StringBuffer sb = new
* StringBuffer();
*
* for (int i = 0; i < files.length; i++) { sb.append(format(files[i]));
* sb.append(NEWLINE); } return sb.toString(); }
*/
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/LISTFileFormater.java | Java | art | 3,318 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl.listing;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Interface for selecting files based on some critera.
*
* @see java.io.FileFilter
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileFilter {
/**
* Decide if the {@link FtpFile} should be selected
*
* @param file
* The {@link FtpFile}
* @return true if the {@link FtpFile} was selected
*/
boolean accept(FtpFile file);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/listing/FileFilter.java | Java | art | 1,392 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>RNFR <SP> <pathname> <CRLF></code><br>
*
* This command specifies the old pathname of the file which is to be renamed.
* This command must be immediately followed by a "rename to" command specifying
* the new file pathname.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RNFR extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(RNFR.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variable
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"RNFR", null));
return;
}
// get filename
FtpFile renFr = null;
try {
renFr = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
// check file
if (renFr == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "RNFR",
fileName));
} else {
session.setRenameFrom(renFr);
fileName = renFr.getAbsolutePath();
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_350_REQUESTED_FILE_ACTION_PENDING_FURTHER_INFORMATION,
"RNFR", fileName));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/RNFR.java | Java | art | 3,450 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Protection buffer size.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PBSZ extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "PBSZ", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PBSZ.java | Java | art | 1,829 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.util.DateUtils;
import org.apache.ftpserver.util.StringUtils;
import org.apache.mina.core.session.IoSession;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Sends the list of all the connected users.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE_WHO extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// only administrator can execute this
UserManager userManager = context.getUserManager();
boolean isAdmin = userManager.isAdmin(session.getUser().getName());
if (!isAdmin) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_530_NOT_LOGGED_IN, "SITE", null));
return;
}
// print all the connected user information
StringBuffer sb = new StringBuffer();
Map<Long, IoSession> sessions = session.getService()
.getManagedSessions();
sb.append('\n');
Iterator<IoSession> sessionIterator = sessions.values().iterator();
while (sessionIterator.hasNext()) {
FtpIoSession managedSession = new FtpIoSession(sessionIterator
.next(), context);
if (!managedSession.isLoggedIn()) {
continue;
}
User tmpUsr = managedSession.getUser();
sb.append(StringUtils.pad(tmpUsr.getName(), ' ', true, 16));
if (managedSession.getRemoteAddress() instanceof InetSocketAddress) {
sb.append(StringUtils.pad(((InetSocketAddress) managedSession
.getRemoteAddress()).getAddress().getHostAddress(),
' ', true, 16));
}
sb.append(StringUtils.pad(DateUtils.getISO8601Date(managedSession
.getLoginTime().getTime()), ' ', true, 20));
sb.append(StringUtils.pad(DateUtils.getISO8601Date(managedSession
.getLastAccessTime().getTime()), ' ', true, 20));
sb.append('\n');
}
sb.append('\n');
session.write(new DefaultFtpReply(FtpReply.REPLY_200_COMMAND_OKAY, sb
.toString()));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE_WHO.java | Java | art | 3,926 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Client-Server listing negotation. Instruct the server what listing types to
* include in machine directory/file listings.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class OPTS_MLST extends AbstractCommand {
private final static String[] AVAILABLE_TYPES = { "Size", "Modify", "Type",
"Perm" };
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// get the listing types
String argument = request.getArgument();
int spIndex = argument.indexOf(' ');
if (spIndex == -1) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS, "OPTS.MLST",
null));
return;
}
String listTypes = argument.substring(spIndex + 1);
// parse all the type tokens
StringTokenizer st = new StringTokenizer(listTypes, ";");
String types[] = new String[st.countTokens()];
for (int i = 0; i < types.length; ++i) {
types[i] = st.nextToken();
}
// set the list types
String[] validatedTypes = validateSelectedTypes(types);
if (validatedTypes != null) {
session.setAttribute("MLST.types", validatedTypes);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "OPTS.MLST", listTypes));
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"OPTS.MLST", listTypes));
}
}
private String[] validateSelectedTypes(final String types[]) {
// ignore null types
if (types == null) {
return null;
}
// check all the types
for (int i = 0; i < types.length; ++i) {
boolean bMatch = false;
for (int j = 0; j < AVAILABLE_TYPES.length; ++j) {
if (AVAILABLE_TYPES[j].equals(types[i])) {
bMatch = true;
break;
}
}
if (!bMatch) {
return null;
}
}
// set the user types
String[] selectedTypes = new String[types.length];
System.arraycopy(types, 0, selectedTypes, 0, types.length);
return selectedTypes;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/OPTS_MLST.java | Java | art | 4,002 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The FEAT command (introduced in [RFC-2389]) allows servers with additional
* features to advertise these to a client by responding to the FEAT command. If
* a server supports the FEAT command then it MUST advertise supported AUTH,
* PBSZ and PROT commands in the reply.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FEAT extends AbstractCommand {
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_211_SYSTEM_STATUS_REPLY, "FEAT", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/FEAT.java | Java | art | 2,079 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.ftpserver.DataConnectionException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerDataConnectionFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The EPSV command requests that a server listen on a data port and wait for a
* connection. The EPSV command takes an optional argument. The response to this
* command includes only the TCP port number of the listening connection. The
* format of the response, however, is similar to the argument of the EPRT
* command. This allows the same parsing routines to be used for both commands.
* In addition, the format leaves a place holder for the network protocol and/or
* network address, which may be needed in the EPSV response in the future. The
* response code for entering passive mode using an extended address MUST be
* 229.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class EPSV extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// set data connection
ServerDataConnectionFactory dataCon = session.getDataConnection();
try {
InetSocketAddress dataConAddress = dataCon
.initPassiveDataConnection();
// get connection info
int servPort = dataConAddress.getPort();
// send connection info to client
String portStr = "|||" + servPort + '|';
session.write(LocalizedFtpReply.translate(session, request, context,
229, "EPSV", portStr));
} catch (DataConnectionException e) {
session
.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION,
"EPSV", null));
return;
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/EPSV.java | Java | art | 3,257 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.DataConnectionException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerDataConnectionFactory;
import org.apache.ftpserver.util.SocketAddressEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>PASV <CRLF></code><br>
*
* This command requests the server-DTP to "listen" on a data port (which is not
* its default data port) and to wait for a connection rather than initiate one
* upon receipt of a transfer command. The response to this command includes the
* host and port address this server is listening on.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PASV extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(PASV.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// set data connection
ServerDataConnectionFactory dataCon = session.getDataConnection();
String externalPassiveAddress = session.getListener()
.getDataConnectionConfiguration().getPassiveExernalAddress();
try {
InetSocketAddress dataConAddress = dataCon
.initPassiveDataConnection();
// get connection info
InetAddress servAddr;
if (externalPassiveAddress != null) {
servAddr = resolveAddress(externalPassiveAddress);
} else {
servAddr = dataConAddress.getAddress();
}
// send connection info to client
InetSocketAddress externalDataConAddress = new InetSocketAddress(
servAddr, dataConAddress.getPort());
String addrStr = SocketAddressEncoder
.encode(externalDataConAddress);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_227_ENTERING_PASSIVE_MODE, "PASV", addrStr));
} catch (DataConnectionException e) {
LOG.warn("Failed to open passive data connection", e);
session
.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION,
"PASV", null));
return;
}
}
/*
* (non-Javadoc)
* Returns an InetAddress object from a hostname or IP address.
*/
private InetAddress resolveAddress(String host) throws DataConnectionException{
try{
return InetAddress.getByName(host);
}catch(UnknownHostException ex){
throw new DataConnectionException(ex.getLocalizedMessage(),ex);
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PASV.java | Java | art | 4,260 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerDataConnectionFactory;
import org.apache.ftpserver.ssl.SslConfiguration;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Data channel protection level.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PROT extends AbstractCommand {
private SslConfiguration getSslConfiguration(final FtpIoSession session) {
DataConnectionConfiguration dataCfg = session.getListener().getDataConnectionConfiguration();
SslConfiguration configuration = dataCfg.getSslConfiguration();
// fall back if no configuration has been provided on the data connection config
if(configuration == null) {
configuration = session.getListener().getSslConfiguration();
}
return configuration;
}
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// check argument
String arg = request.getArgument();
if (arg == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"PROT", null));
return;
}
// check argument
arg = arg.toUpperCase();
ServerDataConnectionFactory dcon = session.getDataConnection();
if (arg.equals("C")) {
dcon.setSecure(false);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "PROT", null));
} else if (arg.equals("P")) {
if (getSslConfiguration(session) == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
431, "PROT", null));
} else {
dcon.setSecure(true);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "PROT", null));
}
} else {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"PROT", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PROT.java | Java | art | 3,964 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.usermanager.impl.TransferRateRequest;
import org.apache.ftpserver.usermanager.impl.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This SITE command returns the specified user information.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE_DESCUSER extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(SITE_DESCUSER.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state variables
session.resetState();
// only administrator can execute this
UserManager userManager = context.getUserManager();
boolean isAdmin = userManager.isAdmin(session.getUser().getName());
if (!isAdmin) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_530_NOT_LOGGED_IN, "SITE", null));
return;
}
// get the user name
String argument = request.getArgument();
int spIndex = argument.indexOf(' ');
if (spIndex == -1) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_503_BAD_SEQUENCE_OF_COMMANDS,
"SITE.DESCUSER", null));
return;
}
String userName = argument.substring(spIndex + 1);
// check the user existance
UserManager usrManager = context.getUserManager();
User user = null;
try {
if (usrManager.doesExist(userName)) {
user = usrManager.getUserByName(userName);
}
} catch (FtpException ex) {
LOG.debug("Exception trying to get user from user manager", ex);
user = null;
}
if (user == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"SITE.DESCUSER", userName));
return;
}
// send the user information
StringBuffer sb = new StringBuffer(128);
sb.append("\n");
sb.append("userid : ").append(user.getName()).append("\n");
sb.append("userpassword : ********\n");
sb.append("homedirectory : ").append(user.getHomeDirectory()).append(
"\n");
sb.append("writepermission : ").append(
user.authorize(new WriteRequest()) != null).append("\n");
sb.append("enableflag : ").append(user.getEnabled()).append("\n");
sb.append("idletime : ").append(user.getMaxIdleTime()).append(
"\n");
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) session.getUser()
.authorize(transferRateRequest);
if (transferRateRequest != null) {
sb.append("uploadrate : ").append(
transferRateRequest.getMaxUploadRate()).append("\n");
sb.append("downloadrate : ").append(
transferRateRequest.getMaxDownloadRate()).append("\n");
} else {
sb.append("uploadrate : 0\n");
sb.append("downloadrate : 0\n");
}
sb.append('\n');
session.write(new DefaultFtpReply(FtpReply.REPLY_200_COMMAND_OKAY, sb
.toString()));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE_DESCUSER.java | Java | art | 5,059 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.File;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname to be created as
* a directory (if the pathname is absolute) or as a subdirectory of the current
* working directory (if the pathname is relative).
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MKD extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MKD.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// argument check
String fileName = request.getArgument();
if (fileName == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MKD", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"MKD.invalid", fileName));
return;
}
// check permission
fileName = file.getAbsolutePath();
if (!file.isWritable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"MKD.permission", fileName));
return;
}
// check file existance
if (file.doesExist()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"MKD.exists", fileName));
return;
}
// now create directory
if (file.mkdir()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_257_PATHNAME_CREATED, "MKD", fileName));
// write log message
String userName = session.getUser().getName();
LOG.info("Directory create : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
ftpStat.setMkdir(session, file);
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD",
fileName));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MKD.java | Java | art | 4,459 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.Structure;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>STRU <SP> <structure-code> <CRLF></code><br>
*
* The argument is a single Telnet character code specifying file structure.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class STRU extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(STRU.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// argument check
if (!request.hasArgument()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"STRU", null));
return;
}
// set structure
char stru = request.getArgument().charAt(0);
try {
session.setStructure(Structure.parseArgument(stru));
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "STRU", null));
} catch (IllegalArgumentException e) {
LOG
.debug("Illegal structure argument: "
+ request.getArgument(), e);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"STRU", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/STRU.java | Java | art | 3,133 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.command.impl.listing.DirectoryLister;
import org.apache.ftpserver.command.impl.listing.LISTFileFormater;
import org.apache.ftpserver.command.impl.listing.ListArgument;
import org.apache.ftpserver.command.impl.listing.ListArgumentParser;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>STAT [<SP> <pathname>] <CRLF></code><br>
*
* This command shall cause a status response to be sent over the control
* connection in the form of a reply.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class STAT extends AbstractCommand {
private static final LISTFileFormater LIST_FILE_FORMATER = new LISTFileFormater();
private DirectoryLister directoryLister = new DirectoryLister();
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
if(request.getArgument() != null) {
ListArgument parsedArg = ListArgumentParser.parse(request.getArgument());
// check that the directory or file exists
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(parsedArg.getFile());
if(!file.doesExist()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "LIST",
null));
return;
}
String dirList = directoryLister.listFiles(parsedArg,
session.getFileSystemView(), LIST_FILE_FORMATER);
session
.write(new DefaultFtpReply(
FtpReply.REPLY_200_COMMAND_OKAY,
dirList));
} catch (FtpException e) {
session.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN,
"STAT", null));
}
} else {
// write the status info
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_211_SYSTEM_STATUS_REPLY, "STAT", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/STAT.java | Java | art | 3,978 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.message.MessageResource;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>HELP [<SP> <string>] <CRLF></code><br>
*
* This command shall cause the server to send helpful information regarding its
* implementation status over the control connection to the user. The command
* may take an argument (e.g., any command name) and return more specific
* information as a response.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class HELP extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// print global help
if (!request.hasArgument()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_214_HELP_MESSAGE, null, null));
return;
}
// print command specific help if available
String ftpCmd = request.getArgument().toUpperCase();
MessageResource resource = context.getMessageResource();
if (resource.getMessage(FtpReply.REPLY_214_HELP_MESSAGE, ftpCmd,
session.getLanguage()) == null) {
ftpCmd = null;
}
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_214_HELP_MESSAGE, ftpCmd, null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/HELP.java | Java | art | 2,737 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>NOOP <CRLF></code><br>
*
* This command does not affect any parameters or previously entered commands.
* It specifies no action other than that the server send an OK reply.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class NOOP extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "NOOP", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/NOOP.java | Java | art | 1,993 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.command.impl.listing.DirectoryLister;
import org.apache.ftpserver.command.impl.listing.FileFormater;
import org.apache.ftpserver.command.impl.listing.ListArgument;
import org.apache.ftpserver.command.impl.listing.ListArgumentParser;
import org.apache.ftpserver.command.impl.listing.MLSTFileFormater;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.IODataConnectionFactory;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>MLSD [<SP> <pathname>] <CRLF></code><br>
*
* This command causes a list to be sent from the server to the passive DTP. The
* pathname must specify a directory and the server should transfer a list of
* files in the specified directory. A null argument implies the user's current
* working or default directory. The data transfer is over the data connection
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MLSD extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MLSD.class);
private DirectoryLister directoryLister = new DirectoryLister();
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// reset state
session.resetState();
// 24-10-2007 - added check if PORT or PASV is issued, see
// https://issues.apache.org/jira/browse/FTPSERVER-110
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"));
return;
}
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "MLSD", null));
// print listing data
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception getting the output data stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "MLSD",
null));
return;
}
boolean failure = false;
try {
// parse argument
ListArgument parsedArg = ListArgumentParser.parse(request
.getArgument());
FileFormater formater = new MLSTFileFormater((String[]) session
.getAttribute("MLST.types"));
dataConnection.transferToClient(session.getFtpletSession(), directoryLister.listFiles(
parsedArg, session.getFileSystemView(), formater));
} catch (SocketException ex) {
LOG.debug("Socket exception during data transfer", ex);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"MLSD", null));
} catch (IOException ex) {
LOG.debug("IOException during data transfer", ex);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"MLSD", null));
} catch (IllegalArgumentException e) {
LOG
.debug("Illegal listing syntax: "
+ request.getArgument(), e);
// if listing syntax error - send message
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MLSD", null));
}
// if data transfer ok - send transfer complete message
if (!failure) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_226_CLOSING_DATA_CONNECTION, "MLSD",
null));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MLSD.java | Java | art | 6,817 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.apache.ftpserver.impl.ServerFtpStatistics;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginRequest;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>USER <SP> <username> <CRLF></code><br>
*
* The argument field is a Telnet string identifying the user. The user
* identification is that which is required by the server for access to its file
* system. This command will normally be the first command transmitted by the
* user after the control connections are made.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class USER extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(USER.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
boolean success = false;
ServerFtpStatistics stat = (ServerFtpStatistics) context
.getFtpStatistics();
try {
// reset state variables
session.resetState();
// argument check
String userName = request.getArgument();
if (userName == null) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"USER", null));
return;
}
// Add to the MDC logging
MdcInjectionFilter.setProperty(session, "userName", userName);
// already logged-in
User user = session.getUser();
if (session.isLoggedIn()) {
if (userName.equals(user.getName())) {
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_230_USER_LOGGED_IN, "USER",
null));
success = true;
} else {
session.write(LocalizedFtpReply.translate(session, request,
context, 530, "USER.invalid", null));
}
return;
}
// anonymous login is not enabled
boolean anonymous = userName.equals("anonymous");
if (anonymous
&& (!context.getConnectionConfig()
.isAnonymousLoginEnabled())) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_530_NOT_LOGGED_IN, "USER.anonymous",
null));
return;
}
// anonymous login limit check
int currAnonLogin = stat.getCurrentAnonymousLoginNumber();
int maxAnonLogin = context.getConnectionConfig()
.getMaxAnonymousLogins();
if(maxAnonLogin == 0) {
LOG.debug("Currently {} anonymous users logged in, unlimited allowed", currAnonLogin);
} else {
LOG.debug("Currently {} out of {} anonymous users logged in", currAnonLogin, maxAnonLogin);
}
if (anonymous && (currAnonLogin >= maxAnonLogin)) {
LOG.debug("Too many anonymous users logged in, user will be disconnected");
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION,
"USER.anonymous", null));
return;
}
// login limit check
int currLogin = stat.getCurrentLoginNumber();
int maxLogin = context.getConnectionConfig().getMaxLogins();
if(maxLogin == 0) {
LOG.debug("Currently {} users logged in, unlimited allowed", currLogin);
} else {
LOG.debug("Currently {} out of {} users logged in", currLogin, maxLogin);
}
if (maxLogin != 0 && currLogin >= maxLogin) {
LOG.debug("Too many users logged in, user will be disconnected");
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION,
"USER.login", null));
return;
}
User configUser = context.getUserManager().getUserByName(userName);
if (configUser != null) {
// user login limit check
InetAddress address = null;
if (session.getRemoteAddress() instanceof InetSocketAddress) {
address = ((InetSocketAddress) session.getRemoteAddress())
.getAddress();
}
ConcurrentLoginRequest loginRequest = new ConcurrentLoginRequest(
stat.getCurrentUserLoginNumber(configUser) + 1,
stat.getCurrentUserLoginNumber(configUser, address) + 1);
if (configUser.authorize(loginRequest) == null) {
LOG.debug("User logged in too many sessions, user will be disconnected");
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_421_SERVICE_NOT_AVAILABLE_CLOSING_CONTROL_CONNECTION,
"USER.login", null));
return;
}
}
// finally set the user name
success = true;
session.setUserArgument(userName);
if (anonymous) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_331_USER_NAME_OKAY_NEED_PASSWORD,
"USER.anonymous", userName));
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_331_USER_NAME_OKAY_NEED_PASSWORD,
"USER", userName));
}
} finally {
// if not ok - close connection
if (!success) {
LOG.debug("User failed to login, session will be closed");
session.close(false).awaitUninterruptibly(10000);
}
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/USER.java | Java | art | 8,798 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver.command.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.impl.FtpServerContext;
import org.apache.ftpserver.impl.LocalizedFtpReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The EPRT command allows for the specification of an extended address for the
* data connection. The extended address MUST consist of the network protocol as
* well as the network and transport addresses. The format of EPRT is:
*
* EPRT<space><d><net-prt><d><net-addr><d><tcp-port><d>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class EPRT extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(EPRT.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// argument check
String arg = request.getArgument();
if (arg == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"EPRT", null));
return;
}
// is port enabled
DataConnectionConfiguration dataCfg = session.getListener()
.getDataConnectionConfiguration();
if (!dataCfg.isActiveEnabled()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "EPRT.disabled", null));
return;
}
// parse argument
String host = null;
String port = null;
try {
char delim = arg.charAt(0);
int lastDelimIdx = arg.indexOf(delim, 3);
host = arg.substring(3, lastDelimIdx);
port = arg.substring(lastDelimIdx + 1, arg.length() - 1);
} catch (Exception ex) {
LOG.debug("Exception parsing host and port: " + arg, ex);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "EPRT", null));
return;
}
// get data server
InetAddress dataAddr = null;
try {
dataAddr = InetAddress.getByName(host);
} catch (UnknownHostException ex) {
LOG.debug("Unknown host: " + host, ex);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"EPRT.host", null));
return;
}
// check IP
if (dataCfg.isActiveIpCheck()) {
if (session.getRemoteAddress() instanceof InetSocketAddress) {
InetAddress clientAddr = ((InetSocketAddress) session
.getRemoteAddress()).getAddress();
if (!dataAddr.equals(clientAddr)) {
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "EPRT.mismatch", null));
return;
}
}
}
// get data server port
int dataPort = 0;
try {
dataPort = Integer.parseInt(port);
} catch (NumberFormatException ex) {
LOG.debug("Invalid port: " + port, ex);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"EPRT.invalid", null));
return;
}
session.getDataConnection().initActiveDataConnection(
new InetSocketAddress(dataAddr, dataPort));
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "EPRT", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/EPRT.java | Java | art | 5,695 |