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.command.impl;
import java.io.IOException;
import org.apache.ftpserver.command.AbstractCommand;
import org.apache.ftpserver.ftplet.DataType;
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>TYPE <SP> <type-code> <CRLF></code><br>
*
* The argument specifies the representation type.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TYPE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(TYPE.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// get type from argument
char type;
if (request.hasArgument()) {
type = request.getArgument().charAt(0);
}else{
// no type specified
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"TYPE", null));
return;
}
// set type
try {
session.setDataType(DataType.parseArgument(type));
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "TYPE", null));
} catch (IllegalArgumentException e) {
LOG.debug("Illegal type argument: " + request.getArgument(), e);
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_504_COMMAND_NOT_IMPLEMENTED_FOR_THAT_PARAMETER,
"TYPE", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/TYPE.java | Java | art | 3,248 |
/*
* 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.ParseException;
import java.util.Date;
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.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Command for changing the modified time of a file.
* <p>
* Specified in the following document:
* http://www.omz13.com/downloads/draft-somers-ftp-mfxx-00.html#anchor8
* </p>
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MFMT extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MFMT.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
String argument = request.getArgument();
if (argument == null || argument.trim().length() == 0) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MFMT.invalid", null));
return;
}
String[] arguments = argument.split(" ",2);
if(arguments.length != 2) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MFMT.invalid", null));
return;
}
String timestamp = arguments[0].trim();
try {
Date time = DateUtils.parseFTPDate(timestamp);
String fileName = arguments[1].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 || !file.doesExist()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"MFMT.filemissing", fileName));
return;
}
// check file
if (!file.isFile()) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MFMT.invalid", null));
return;
}
// check if we can set date and retrieve the actual date stored for the file.
if (!file.setLastModified(time.getTime())) {
// we couldn't set the date, possibly the file was locked
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "MFMT",
fileName));
return;
}
// all checks okay, lets go
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_213_FILE_STATUS,
"MFMT", "ModifyTime=" + timestamp + "; " + fileName));
return;
} catch (ParseException e) {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MFMT.invalid", null));
return;
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MFMT.java | Java | art | 5,810 |
/*
* 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.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.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>MLST <SP> <pathname> <CRLF></code><br>
*
* Returns info on the file over the control connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MLST extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MLST.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// reset state variables
session.resetState();
// parse argument
ListArgument parsedArg = ListArgumentParser
.parse(request.getArgument());
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(
parsedArg.getFile());
if (file != null && file.doesExist()) {
FileFormater formater = new MLSTFileFormater((String[]) session
.getAttribute("MLST.types"));
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "MLST",
formater.format(file)));
} else {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MLST", null));
}
} catch (FtpException ex) {
LOG.debug("Exception sending the file listing", ex);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"MLST", null));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/MLST.java | Java | art | 3,668 |
/*
* 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;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <code>PWD <CRLF></code><br>
*
* This command causes the name of the current working directory to be returned
* in the reply.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PWD extends AbstractCommand {
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
session.resetState();
FileSystemView fsview = session.getFileSystemView();
String currDir = fsview.getWorkingDirectory().getAbsolutePath();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_257_PATHNAME_CREATED, "PWD", currDir));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/PWD.java | Java | art | 2,130 |
/*
* 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>
*
* Client-Server encoding negotiation. Force server from default encoding to
* UTF-8 and back. Note that the servers default encoding is UTF-8. So this
* command has no effect.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class OPTS_UTF8 extends AbstractCommand {
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
// reset state
session.resetState();
// send default message
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "OPTS.UTF8", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/OPTS_UTF8.java | Java | art | 2,047 |
/*
* 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>
*
* Handle SITE command.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SITE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(SITE.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 {
// get request name
String argument = request.getArgument();
if (argument != null) {
int spaceIndex = argument.indexOf(' ');
if (spaceIndex != -1) {
argument = argument.substring(0, spaceIndex);
}
argument = argument.toUpperCase();
}
// no params
if (argument == null) {
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_200_COMMAND_OKAY, "SITE", null));
return;
}
// call appropriate command method
String siteRequest = "SITE_" + argument;
Command command = (Command) COMMAND_MAP.get(siteRequest);
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, "SITE",
argument));
}
} catch (Exception ex) {
LOG.warn("SITE.execute()", ex);
session.resetState();
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_500_SYNTAX_ERROR_COMMAND_UNRECOGNIZED,
"SITE", null));
}
}
// initialize all the SITE command handlers
static {
COMMAND_MAP.put("SITE_DESCUSER",
new org.apache.ftpserver.command.impl.SITE_DESCUSER());
COMMAND_MAP.put("SITE_HELP",
new org.apache.ftpserver.command.impl.SITE_HELP());
COMMAND_MAP.put("SITE_STAT",
new org.apache.ftpserver.command.impl.SITE_STAT());
COMMAND_MAP
.put("SITE_WHO", new org.apache.ftpserver.command.impl.SITE_WHO());
COMMAND_MAP.put("SITE_ZONE",
new org.apache.ftpserver.command.impl.SITE_ZONE());
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/SITE.java | Java | art | 4,011 |
/*
* 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>ACCT <CRLF></code><br>
*
* Acknowledges the ACCT (account) command with a 202 reply. The command however
* is irrelevant to any workings.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ACCT 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.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_202_COMMAND_NOT_IMPLEMENTED, "ACCT", null));
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/ACCT.java | Java | art | 1,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.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>REST <SP> <marker> <CRLF></code><br>
*
* The argument field represents the server marker at which file transfer is to
* be restarted. This command does not cause file transfer but skips over the
* file to the specified data checkpoint. This command shall be immediately
* followed by the appropriate FTP service command which shall cause file
* transfer to resume.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class REST extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(REST.class);
/**
* Execute command
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException {
// argument check
String argument = request.getArgument();
if (argument == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"REST", null));
return;
}
// get offset number
session.resetState();
long skipLen = 0L;
try {
skipLen = Long.parseLong(argument);
// check offset number
if (skipLen < 0L) {
skipLen = 0L;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"REST.negetive", null));
} else {
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_350_REQUESTED_FILE_ACTION_PENDING_FURTHER_INFORMATION,
"REST", null));
}
} catch (NumberFormatException ex) {
LOG.debug("Invalid restart position: " + argument, ex);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS,
"REST.invalid", null));
}
session.setFileOffset(skipLen);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/REST.java | Java | art | 3,929 |
/*
* 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>DELE <SP> <pathname> <CRLF></code><br>
*
* This command causes the file specified in the pathname to be deleted at the
* server site.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DELE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(DELE.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,
"DELE", null));
return;
}
// get file object
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception ex) {
LOG.debug("Could not get file " + fileName, ex);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"DELE.invalid", fileName));
return;
}
// check file
fileName = file.getAbsolutePath();
if (file.isDirectory()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"DELE.invalid", fileName));
return;
}
if (!file.isRemovable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN,
"DELE.permission", fileName));
return;
}
// now delete
if (file.delete()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "DELE",
fileName));
// log message
String userName = session.getUser().getName();
LOG.info("File delete : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics) context
.getFtpStatistics();
ftpStat.setDelete(session, file);
} else {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_450_REQUESTED_FILE_ACTION_NOT_TAKEN, "DELE",
fileName));
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/DELE.java | Java | art | 4,345 |
/*
* 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>APPE <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 in a file at the server site. If the
* file specified in the pathname exists at the server site, then the data shall
* be appended to that file; otherwise the file specified in the pathname shall
* be created at the server site.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class APPE extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(APPE.class);
/**
* Execute command.
*/
public void execute(final FtpIoSession session,
final FtpServerContext context, final FtpRequest request)
throws IOException, FtpException {
try {
// 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,
"APPE", 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 filenames
FtpFile file = null;
try {
file = session.getFileSystemView().getFile(fileName);
} catch (Exception e) {
LOG.debug("File system threw exception", e);
}
if (file == null) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.invalid", fileName));
return;
}
fileName = file.getAbsolutePath();
// check file existance
if (file.doesExist() && !file.isFile()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.invalid", fileName));
return;
}
// check permission
if (!file.isWritable()) {
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
"APPE.permission", fileName));
return;
}
// get data connection
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_150_FILE_STATUS_OKAY, "APPE", fileName));
DataConnection dataConnection;
try {
dataConnection = session.getDataConnection().openConnection();
} catch (Exception e) {
LOG.debug("Exception when getting data input stream", e);
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_425_CANT_OPEN_DATA_CONNECTION, "APPE",
fileName));
return;
}
// get data from client
boolean failure = false;
OutputStream os = null;
try {
// find offset
long offset = 0L;
if (file.doesExist()) {
offset = file.getSize();
}
// open streams
os = file.createOutputStream(offset);
// 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();
ftpStat.setUpload(session, file, transSz);
} catch (SocketException e) {
LOG.debug("SocketException during file upload", e);
failure = true;
session.write(LocalizedFtpReply.translate(session, request, context,
FtpReply.REPLY_426_CONNECTION_CLOSED_TRANSFER_ABORTED,
"APPE", fileName));
} catch (IOException e) {
LOG.debug("IOException during file upload", e);
failure = true;
session
.write(LocalizedFtpReply
.translate(
session,
request,
context,
FtpReply.REPLY_551_REQUESTED_ACTION_ABORTED_PAGE_TYPE_UNKNOWN,
"APPE", 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, "APPE",
fileName));
}
} finally {
session.getDataConnection().closeDataConnection();
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/impl/APPE.java | Java | art | 8,422 |
/*
* 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;
/**
* Common base class recommended for {@link Command} implementations
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public abstract class AbstractCommand implements Command {
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/command/AbstractCommand.java | Java | art | 1,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;
import java.net.InetAddress;
import org.apache.ftpserver.ssl.SslConfiguration;
/**
* Data connection configuration interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface DataConnectionConfiguration {
/**
* Get the maximum idle time in seconds.
* @return The maximum idle time
*/
int getIdleTime();
/**
* Is active data connection enabled?
* @return true if active data connections are enabled
*/
boolean isActiveEnabled();
/**
* Check the PORT IP with the client IP?
* @return true if the PORT IP is verified
*/
boolean isActiveIpCheck();
/**
* Get the active data connection local host.
* @return The {@link InetAddress} for active connections
*/
String getActiveLocalAddress();
/**
* Get the active data connection local port.
* @return The active data connection local port
*/
int getActiveLocalPort();
/**
* Get passive server address. null, if not set in the configuration.
* @return The {@link InetAddress} used for passive connections
*/
String getPassiveAddress();
/**
* Get the passive address that will be returned to clients on the PASV
* command.
*
* @return The passive address to be returned to clients, null if not
* configured.
*/
String getPassiveExernalAddress();
/**
* Get the passive ports to be used for data connections. Ports can be
* defined as single ports, closed or open ranges. Multiple definitions can
* be separated by commas, for example:
* <ul>
* <li>2300 : only use port 2300 as the passive port</li>
* <li>2300-2399 : use all ports in the range</li>
* <li>2300- : use all ports larger than 2300</li>
* <li>2300, 2305, 2400- : use 2300 or 2305 or any port larger than 2400</li>
* </ul>
*
* Defaults to using any available port
*
* @return The passive ports string
*/
String getPassivePorts();
/**
* Request a passive port. Will block until a port is available
* @return A free passive part
*/
int requestPassivePort();
/**
* Release passive port.
* @param port The port to be released
*/
void releasePassivePort(int port);
/**
* Get SSL configuration for this data connection.
* @return The {@link SslConfiguration}
*/
SslConfiguration getSslConfiguration();
/**
* @return True if SSL is mandatory for the data channel
*/
boolean isImplicitSsl();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/DataConnectionConfiguration.java | Java | art | 3,441 |
/*
* 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.ftplet.FtpException;
/**
* Thrown if a data connection can not be established
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DataConnectionException extends FtpException {
private static final long serialVersionUID = -1328383839917648987L;
/**
* Default constructor.
*/
public DataConnectionException() {
super();
}
/**
* Constructs a <code>DataConnectionException</code> object with a message.
*
* @param msg
* a description of the exception
*/
public DataConnectionException(final String msg) {
super(msg);
}
/**
* Constructs a <code>DataConnectionException</code> object with a
* <code>Throwable</code> cause.
*
* @param th
* the original cause
*/
public DataConnectionException(final Throwable th) {
super(th);
}
/**
* Constructs a <code>DataConnectionException</code> object with a
* <code>Throwable</code> cause.
* @param msg a description of the exception
*
* @param th
* the original cause
*/
public DataConnectionException(final String msg, final Throwable th) {
super(msg, th);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/DataConnectionException.java | Java | art | 2,127 |
/*
* 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.ftplet.FtpException;
/**
* This is the starting point of all the servers. It invokes a new listener
* thread. <code>Server</code> implementation is used to create the server
* socket and handle client connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpServer {
/**
* Start the server. Open a new listener thread.
* @throws FtpException
*/
void start() throws FtpException;
/**
* Stop the server. Stop the listener thread.
*/
void stop();
/**
* Get the server status.
* @return true if the server is stopped
*/
boolean isStopped();
/**
* Suspend further requests
*/
void suspend();
/**
* Resume the server handler
*/
void resume();
/**
* Is the server suspended
* @return true if the server is suspended
*/
boolean isSuspended();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/FtpServer.java | Java | art | 1,815 |
/*
* 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 java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.impl.DefaultDataConnectionConfiguration;
import org.apache.ftpserver.impl.PassivePorts;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Data connection factory
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DataConnectionConfigurationFactory {
private Logger log = LoggerFactory.getLogger(DataConnectionConfigurationFactory.class);
// maximum idle time in seconds
private int idleTime = 300;
private SslConfiguration ssl;
private boolean activeEnabled = true;
private String activeLocalAddress;
private int activeLocalPort = 0;
private boolean activeIpCheck = false;
private String passiveAddress;
private String passiveExternalAddress;
private PassivePorts passivePorts = new PassivePorts(new int[] { 0 }, true);
private boolean implicitSsl;
/**
* Create a {@link DataConnectionConfiguration} instance based on the
* configuration on this factory
* @return The {@link DataConnectionConfiguration} instance
*/
public DataConnectionConfiguration createDataConnectionConfiguration() {
checkValidAddresses();
return new DefaultDataConnectionConfiguration(idleTime,
ssl, activeEnabled, activeIpCheck,
activeLocalAddress, activeLocalPort,
passiveAddress, passivePorts,
passiveExternalAddress, implicitSsl);
}
/*
* (Non-Javadoc)
* Checks if the configured addresses to be used in further data connections
* are valid.
*/
private void checkValidAddresses(){
try{
InetAddress.getByName(passiveAddress);
InetAddress.getByName(passiveExternalAddress);
}catch(UnknownHostException ex){
throw new FtpServerConfigurationException("Unknown host", ex);
}
}
/**
* Get the maximum idle time in seconds.
* @return The maximum idle time
*/
public int getIdleTime() {
return idleTime;
}
/**
* Set the maximum idle time in seconds.
* @param idleTime The maximum idle time
*/
public void setIdleTime(int idleTime) {
this.idleTime = idleTime;
}
/**
* Is PORT enabled?
* @return true if active data connections are enabled
*/
public boolean isActiveEnabled() {
return activeEnabled;
}
/**
* Set if active data connections are enabled
* @param activeEnabled true if active data connections are enabled
*/
public void setActiveEnabled(boolean activeEnabled) {
this.activeEnabled = activeEnabled;
}
/**
* Check the PORT IP?
* @return true if the client IP is verified against the PORT IP
*/
public boolean isActiveIpCheck() {
return activeIpCheck;
}
/**
* Check the PORT IP with the client IP?
* @param activeIpCheck true if the PORT IP should be verified
*/
public void setActiveIpCheck(boolean activeIpCheck) {
this.activeIpCheck = activeIpCheck;
}
/**
* Get the local address for active mode data transfer.
* @return The address used for active data connections
*/
public String getActiveLocalAddress() {
return activeLocalAddress;
}
/**
* Set the active data connection local host.
* @param activeLocalAddress The address for active connections
*/
public void setActiveLocalAddress(String activeLocalAddress) {
this.activeLocalAddress = activeLocalAddress;
}
/**
* Get the active local port number.
* @return The port used for active data connections
*/
public int getActiveLocalPort() {
return activeLocalPort;
}
/**
* Set the active data connection local port.
* @param activeLocalPort The active data connection local port
*/
public void setActiveLocalPort(int activeLocalPort) {
this.activeLocalPort = activeLocalPort;
}
/**
* Get passive host.
* @return The address used for passive data connections
*/
public String getPassiveAddress() {
return passiveAddress;
}
/**
* Set the passive server address.
* @param passiveAddress The address used for passive connections
*/
public void setPassiveAddress(String passiveAddress) {
this.passiveAddress = passiveAddress;
}
/**
* Get the passive address that will be returned to clients on the PASV
* command.
*
* @return The passive address to be returned to clients, null if not
* configured.
*/
public String getPassiveExternalAddress() {
return passiveExternalAddress;
}
/**
* Set the passive address that will be returned to clients on the PASV
* command.
*
* @param passiveExternalAddress The passive address to be returned to clients
*/
public void setPassiveExternalAddress(String passiveExternalAddress) {
this.passiveExternalAddress = passiveExternalAddress;
}
/**
* Get passive data port. Data port number zero (0) means that any available
* port will be used.
* @return A passive port to use
*/
public synchronized int requestPassivePort() {
int dataPort = -1;
int loopTimes = 2;
Thread currThread = Thread.currentThread();
while ((dataPort == -1) && (--loopTimes >= 0)
&& (!currThread.isInterrupted())) {
// search for a free port
dataPort = passivePorts.reserveNextPort();
// no available free port - wait for the release notification
if (dataPort == -1) {
try {
log.info("Out of passive ports, waiting for one to be released. Might be stuck");
wait();
} catch (InterruptedException ex) {
}
}
}
return dataPort;
}
/**
* Retrieve the passive ports configured for this data connection
*
* @return The String of passive ports
*/
public String getPassivePorts() {
return passivePorts.toString();
}
/**
* Set the passive ports to be used for data connections. Ports can be
* defined as single ports, closed or open ranges. Multiple definitions can
* be separated by commas, for example:
* <ul>
* <li>2300 : only use port 2300 as the passive port</li>
* <li>2300-2399 : use all ports in the range</li>
* <li>2300- : use all ports larger than 2300</li>
* <li>2300, 2305, 2400- : use 2300 or 2305 or any port larger than 2400</li>
* </ul>
*
* Defaults to using any available port
*
* @param passivePorts The passive ports string
*/
public void setPassivePorts(String passivePorts) {
this.passivePorts = new PassivePorts(passivePorts, true);
}
/**
* Release data port
* @param port The port to release
*/
public synchronized void releasePassivePort(final int port) {
passivePorts.releasePort(port);
notify();
}
/**
* Get the {@link SslConfiguration} to be used by data connections
* @return The {@link SslConfiguration} used by data connections
*/
public SslConfiguration getSslConfiguration() {
return ssl;
}
/**
* Set the {@link SslConfiguration} to be used by data connections
* @param ssl The {@link SslConfiguration}
*/
public void setSslConfiguration(SslConfiguration ssl) {
this.ssl = ssl;
}
/**
* @return True if ssl is mandatory for the data connection
*/
public boolean isImplicitSsl() {
return implicitSsl;
}
/**
* Set whether ssl is required for the data connection
* @param sslMandatory True if ssl is mandatory for the data connection
*/
public void setImplicitSsl(boolean implicitSsl) {
this.implicitSsl = implicitSsl;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/DataConnectionConfigurationFactory.java | Java | art | 8,974 |
/*
* 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;
/**
* Exception used during startup to indicate that the configuration is not
* correct.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpServerConfigurationException extends RuntimeException {
private static final long serialVersionUID = -1328432839915898987L;
/**
* {@link RuntimeException#RuntimeException()}
*/
public FtpServerConfigurationException() {
super();
}
/**
* {@link RuntimeException#RuntimeException(String, Throwable)}
*/
public FtpServerConfigurationException(final String message,
final Throwable cause) {
super(message, cause);
}
/**
* {@link RuntimeException#RuntimeException(String)}
*/
public FtpServerConfigurationException(final String message) {
super(message);
}
/**
* {@link RuntimeException#RuntimeException(Throwable)}
*/
public FtpServerConfigurationException(final Throwable cause) {
super(cause);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/FtpServerConfigurationException.java | Java | art | 1,860 |
/*
* 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.main;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* Invokes FtpServer as a daemon, running in the background. Used for example
* for the Windows service.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class Daemon {
private static final Logger LOG = LoggerFactory.getLogger(Daemon.class);
private static FtpServer server;
private static Object lock = new Object();
/**
* Main entry point for the daemon
* @param args The arguments
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
if (server == null) {
// get configuration
server = getConfiguration(args);
if (server == null) {
LOG.error("No configuration provided");
throw new FtpException("No configuration provided");
}
}
String command = "start";
if (args != null && args.length > 0) {
command = args[0];
}
if (command.equals("start")) {
LOG.info("Starting FTP server daemon");
server.start();
synchronized (lock) {
lock.wait();
}
} else if (command.equals("stop")) {
synchronized (lock) {
lock.notify();
}
LOG.info("Stopping FTP server daemon");
server.stop();
}
} catch (Throwable t) {
LOG.error("Daemon error", t);
}
}
/**
* Get the configuration object.
*/
private static FtpServer getConfiguration(String[] args) throws Exception {
FtpServer server = null;
if (args == null || args.length < 2) {
LOG.info("Using default configuration....");
server = new FtpServerFactory().createServer();
} else if ((args.length == 2) && args[1].equals("-default")) {
// supported for backwards compatibility, but not documented
System.out
.println("The -default switch is deprecated, please use --default instead");
LOG.info("Using default configuration....");
server = new FtpServerFactory().createServer();
} else if ((args.length == 2) && args[1].equals("--default")) {
LOG.info("Using default configuration....");
server = new FtpServerFactory().createServer();
} else if (args.length == 2) {
LOG.info("Using xml configuration file " + args[1] + "...");
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
args[1]);
if (ctx.containsBean("server")) {
server = (FtpServer) ctx.getBean("server");
} else {
String[] beanNames = ctx.getBeanNamesForType(FtpServer.class);
if (beanNames.length == 1) {
server = (FtpServer) ctx.getBean(beanNames[0]);
} else if (beanNames.length > 1) {
System.out
.println("Using the first server defined in the configuration, named "
+ beanNames[0]);
server = (FtpServer) ctx.getBean(beanNames[0]);
} else {
System.err
.println("XML configuration does not contain a server configuration");
}
}
} else {
throw new FtpException("Invalid configuration option");
}
return server;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/main/Daemon.java | Java | art | 4,756 |
/*
* 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.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.DefaultFtpServer;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.PropertiesUserManager;
import org.apache.ftpserver.usermanager.impl.TransferRatePermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;
/**
* Used to add users to the user manager for a particular FtpServer configuration
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class AddUser extends CommandLine {
/**
* Instance methods only used internaly
*/
protected AddUser() {
}
/**
* Used to add users to the user manager for a particular FtpServer configuration
*
* @param args
* The first element of this array must specify the kind of
* configuration to be used to start the server.
*/
public static void main(String args[]) {
AddUser addUser = new AddUser();
try {
// get configuration
FtpServer server = addUser.getConfiguration(args);
if (server == null) {
return;
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
UserManager um = ((DefaultFtpServer)server).getUserManager();
BaseUser user = new BaseUser();
System.out.println("Asking for details of the new user");
System.out.println();
String userName = askForString(in, "User name:", "User name is mandatory");
if(userName == null) {
return;
}
user.setName(userName);
user.setPassword(askForString(in, "Password:"));
String home = askForString(in, "Home directory:", "Home directory is mandatory");
if(home == null) {
return;
}
user.setHomeDirectory(home);
user.setEnabled(askForBoolean(in, "Enabled (Y/N):"));
user.setMaxIdleTime(askForInt(in, "Max idle time in seconds (0 for none):"));
List<Authority> authorities = new ArrayList<Authority>();
if(askForBoolean(in, "Write permission (Y/N):")) {
authorities.add(new WritePermission());
}
int maxLogins = askForInt(in, "Maximum number of concurrent logins (0 for no restriction)");
int maxLoginsPerIp = askForInt(in, "Maximum number of concurrent logins per IP (0 for no restriction)");
authorities.add(new ConcurrentLoginPermission(maxLogins, maxLoginsPerIp));
int downloadRate = askForInt(in, "Maximum download rate (0 for no restriction)");
int uploadRate = askForInt(in, "Maximum upload rate (0 for no restriction)");
authorities.add(new TransferRatePermission(downloadRate, uploadRate));
user.setAuthorities(authorities);
um.save(user);
if(um instanceof PropertiesUserManager) {
File file = ((PropertiesUserManager) um).getFile();
if(file != null) {
System.out.println("User saved to file: " + file.getAbsolutePath());
} else {
System.err.println("User manager does not have a file configured, will not save user to file");
}
} else {
System.out.println("User saved");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String askForString(BufferedReader in, String question) throws IOException {
System.out.println(question);
return in.readLine();
}
private static String askForString(BufferedReader in, String question, String mandatoryMessage) throws IOException {
String s = askForString(in, question);
if(isEmpty(s)) {
System.err.println(mandatoryMessage);
return null;
} else {
return s;
}
}
private static int askForInt(BufferedReader in, String question) throws IOException {
System.out.println(question);
String intValue = in.readLine();
return Integer.parseInt(intValue);
}
private static boolean askForBoolean(BufferedReader in, String question) throws IOException {
System.out.println(question);
String boolValue = in.readLine();
return "Y".equalsIgnoreCase(boolValue);
}
private static boolean isEmpty(String s) {
if(s == null) {
return true;
} else {
return s.trim().length() == 0;
}
}
/**
* Print the usage message.
*/
protected void usage() {
System.err.println("Usage: java " + AddUser.class.getName() + " [OPTION] [CONFIGFILE]");
System.err
.println("Starts the user management application, asking for user settings");
System.err.println("");
System.err
.println(" --default use the default configuration, ");
System.err
.println(" also used if no command line argument is given ");
System.err.println(" -?, --help print this message");
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/main/AddUser.java | Java | art | 6,720 |
/*
* 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.main;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* This class is the starting point for the FtpServer when it is started using
* the command line mode.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class CommandLine {
/**
* The purpose of this class is to allow the final user to start the
* FtpServer application. Because of that it has only <code>static</code>
* methods and cannot be instanced.
*/
protected CommandLine() {
}
/**
* This method is the FtpServer starting point when running by using the
* command line mode.
*
* @param args
* The first element of this array must specify the kind of
* configuration to be used to start the server.
*/
public static void main(String args[]) {
CommandLine cli = new CommandLine();
try {
// get configuration
FtpServer server = cli.getConfiguration(args);
if (server == null) {
return;
}
// start the server
server.start();
System.out.println("FtpServer started");
// add shutdown hook if possible
cli.addShutdownHook(server);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Add shutdown hook.
*/
private void addShutdownHook(final FtpServer engine) {
// create shutdown hook
Runnable shutdownHook = new Runnable() {
public void run() {
System.out.println("Stopping server...");
engine.stop();
}
};
// add shutdown hook
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread(shutdownHook));
}
/**
* Print the usage message.
*/
protected void usage() {
System.err
.println("Usage: java org.apache.ftpserver.main.CommandLine [OPTION] [CONFIGFILE]");
System.err
.println("Starts FtpServer using the default configuration of the ");
System.err.println("configuration file if provided.");
System.err.println("");
System.err
.println(" --default use the default configuration, ");
System.err
.println(" also used if no command line argument is given ");
System.err.println(" -?, --help print this message");
}
/**
* Get the configuration object.
*/
protected FtpServer getConfiguration(String[] args) throws Exception {
FtpServer server = null;
if (args.length == 0) {
System.out.println("Using default configuration");
server = new FtpServerFactory().createServer();
} else if ((args.length == 1) && args[0].equals("-default")) {
// supported for backwards compatibility, but not documented
System.out
.println("The -default switch is deprecated, please use --default instead");
System.out.println("Using default configuration");
server = new FtpServerFactory().createServer();
} else if ((args.length == 1) && args[0].equals("--default")) {
System.out.println("Using default configuration");
server = new FtpServerFactory().createServer();
} else if ((args.length == 1) && args[0].equals("--help")) {
usage();
} else if ((args.length == 1) && args[0].equals("-?")) {
usage();
} else if (args.length == 1) {
System.out.println("Using XML configuration file " + args[0]
+ "...");
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(
args[0]);
if (ctx.containsBean("server")) {
server = (FtpServer) ctx.getBean("server");
} else {
String[] beanNames = ctx.getBeanNamesForType(FtpServer.class);
if (beanNames.length == 1) {
server = (FtpServer) ctx.getBean(beanNames[0]);
} else if (beanNames.length > 1) {
System.out
.println("Using the first server defined in the configuration, named "
+ beanNames[0]);
server = (FtpServer) ctx.getBean(beanNames[0]);
} else {
System.err
.println("XML configuration does not contain a server configuration");
}
}
} else {
usage();
}
return server;
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/main/CommandLine.java | Java | art | 5,714 |
/*
* 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 java.util.LinkedHashMap;
import java.util.Map;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.ftpletcontainer.impl.DefaultFtpletContainer;
import org.apache.ftpserver.impl.DefaultFtpServer;
import org.apache.ftpserver.impl.DefaultFtpServerContext;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.message.MessageResource;
/**
* This is the starting point of all the servers. Creates server instances based on
* the provided configuration.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FtpServerFactory {
private DefaultFtpServerContext serverContext;
/**
* Creates a server with the default configuration
*
* @throws Exception
*/
public FtpServerFactory() {
serverContext = new DefaultFtpServerContext();
}
/**
* Create a {@link DefaultFtpServer} instance based
* on the provided configuration
* @return The {@link DefaultFtpServer} instance
*/
public FtpServer createServer() {
return new DefaultFtpServer(serverContext);
}
/**
* Get all listeners available on servers created by this factory
*
* @return The current listeners
*/
public Map<String, Listener> getListeners() {
return serverContext.getListeners();
}
/**
* Get a specific {@link Listener} identified by its name
*
* @param name
* The name of the listener
* @return The {@link Listener} matching the provided name
*/
public Listener getListener(final String name) {
return serverContext.getListener(name);
}
/**
* Add a {@link Listener} to this factory
* @param name The name of the listener
* @param listener The {@link Listener}
*/
public void addListener(final String name, final Listener listener) {
serverContext.addListener(name, listener);
}
/**
* Set the listeners for servers created by this factory, replaces existing listeners
*
* @param listeners
* The listeners to use for this server with the name as the key
* and the listener as the value
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setListeners(final Map<String, Listener> listeners) {
serverContext.setListeners(listeners);
}
/**
* Get all {@link Ftplet}s registered by servers created by this factory
*
* @return All {@link Ftplet}s
*/
public Map<String, Ftplet> getFtplets() {
return serverContext.getFtpletContainer().getFtplets();
}
/**
* Set the {@link Ftplet}s to be active by servers created by this factory. Replaces existing
* {@link Ftplet}s
*
* @param ftplets
* Ftplets as a map with the name as the key and the Ftplet as
* the value. The Ftplet container will iterate over the map in the
* order provided by the Map. If invocation order of Ftplets is of importance,
* make sure to provide a ordered Map, for example {@link LinkedHashMap}.
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setFtplets(final Map<String, Ftplet> ftplets) {
serverContext.setFtpletContainer(new DefaultFtpletContainer(ftplets));
}
/**
* Retrieve the user manager used by servers created by this factory
*
* @return The user manager
*/
public UserManager getUserManager() {
return serverContext.getUserManager();
}
/**
* Set the user manager to be used by servers created by this factory
*
* @param userManager
* The {@link UserManager}
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setUserManager(final UserManager userManager) {
serverContext.setUserManager(userManager);
}
/**
* Retrieve the file system used by servers created by this factory
*
* @return The {@link FileSystemFactory}
*/
public FileSystemFactory getFileSystem() {
return serverContext.getFileSystemManager();
}
/**
* Set the file system to be used by servers created by this factory
*
* @param fileSystem
* The {@link FileSystemFactory}
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setFileSystem(final FileSystemFactory fileSystem) {
serverContext.setFileSystemManager(fileSystem);
}
/**
* Retrieve the command factory used by servers created by this factory
*
* @return The {@link CommandFactory}
*/
public CommandFactory getCommandFactory() {
return serverContext.getCommandFactory();
}
/**
* Set the command factory to be used by servers created by this factory
*
* @param commandFactory
* The {@link CommandFactory}
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setCommandFactory(final CommandFactory commandFactory) {
serverContext.setCommandFactory(commandFactory);
}
/**
* Retrieve the message resource used by servers created by this factory
*
* @return The {@link MessageResource}
*/
public MessageResource getMessageResource() {
return serverContext.getMessageResource();
}
/**
* Set the message resource to be used with by servers created by this factory
*
* @param messageResource
* The {@link MessageResource}
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setMessageResource(final MessageResource messageResource) {
serverContext.setMessageResource(messageResource);
}
/**
* Retrieve the connection configuration this server
*
* @return The {@link MessageResource}
*/
public ConnectionConfig getConnectionConfig() {
return serverContext.getConnectionConfig();
}
/**
* Set the message resource to be used with this server
* @param connectionConfig The {@link ConnectionConfig} to be used
* by servers created by this factory
*
* @param messageResource
* The {@link MessageResource}
* @throws IllegalStateException
* If a custom server context has been set
*/
public void setConnectionConfig(final ConnectionConfig connectionConfig) {
serverContext.setConnectionConfig(connectionConfig);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/FtpServerFactory.java | Java | art | 7,785 |
/*
* 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.message.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.message.MessageResource;
import org.apache.ftpserver.message.MessageResourceFactory;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Class to get FtpServer reply messages. This supports i18n. Basic message
* search path is:
*
* <strong><strong>Internal class, do not use directly.</strong></strong>
*
* Custom Language Specific Messages -> Default Language Specific Messages ->
* Custom Common Messages -> Default Common Messages -> null (not found)
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultMessageResource implements MessageResource {
private final Logger LOG = LoggerFactory
.getLogger(DefaultMessageResource.class);
private final static String RESOURCE_PATH = "org/apache/ftpserver/message/";
private List<String> languages;
private Map<String, PropertiesPair> messages;
/**
* Internal constructor, do not use directly. Use {@link MessageResourceFactory} instead.
*/
public DefaultMessageResource(List<String> languages,
File customMessageDirectory) {
if(languages != null) {
this.languages = Collections.unmodifiableList(languages);
}
// populate different properties
messages = new HashMap<String, PropertiesPair>();
if (languages != null) {
for (String language : languages) {
PropertiesPair pair = createPropertiesPair(language, customMessageDirectory);
messages.put(language, pair);
}
}
PropertiesPair pair = createPropertiesPair(null, customMessageDirectory);
messages.put(null, pair);
}
private static class PropertiesPair {
public Properties defaultProperties = new Properties();
public Properties customProperties = new Properties();
}
/**
* Create Properties pair object. It stores the default and the custom
* messages.
*/
private PropertiesPair createPropertiesPair(String lang, File customMessageDirectory) {
PropertiesPair pair = new PropertiesPair();
// load default resource
String defaultResourceName;
if (lang == null) {
defaultResourceName = RESOURCE_PATH + "FtpStatus.properties";
} else {
defaultResourceName = RESOURCE_PATH + "FtpStatus_" + lang
+ ".properties";
}
InputStream in = null;
try {
in = getClass().getClassLoader().getResourceAsStream(
defaultResourceName);
if (in != null) {
try {
pair.defaultProperties.load(in);
} catch (IOException e) {
throw new FtpServerConfigurationException(
"Failed to load messages from \"" + defaultResourceName + "\", file not found in classpath");
}
} else {
throw new FtpServerConfigurationException(
"Failed to load messages from \"" + defaultResourceName + "\", file not found in classpath");
}
} finally {
IoUtils.close(in);
}
// load custom resource
File resourceFile = null;
if (lang == null) {
resourceFile = new File(customMessageDirectory, "FtpStatus.gen");
} else {
resourceFile = new File(customMessageDirectory, "FtpStatus_" + lang
+ ".gen");
}
in = null;
try {
if (resourceFile.exists()) {
in = new FileInputStream(resourceFile);
pair.customProperties.load(in);
}
} catch (Exception ex) {
LOG.warn("MessageResourceImpl.createPropertiesPair()", ex);
throw new FtpServerConfigurationException(
"MessageResourceImpl.createPropertiesPair()", ex);
} finally {
IoUtils.close(in);
}
return pair;
}
/**
* Get all the available languages.
*/
public List<String> getAvailableLanguages() {
if (languages == null) {
return null;
} else {
return Collections.unmodifiableList(languages);
}
}
/**
* Get the message. If the message not found, it will return null.
*/
public String getMessage(int code, String subId, String language) {
// find the message key
String key = String.valueOf(code);
if (subId != null) {
key = key + '.' + subId;
}
// get language specific value
String value = null;
PropertiesPair pair = null;
if (language != null) {
language = language.toLowerCase();
pair = messages.get(language);
if (pair != null) {
value = pair.customProperties.getProperty(key);
if (value == null) {
value = pair.defaultProperties.getProperty(key);
}
}
}
// if not available get the default value
if (value == null) {
pair = messages.get(null);
if (pair != null) {
value = pair.customProperties.getProperty(key);
if (value == null) {
value = pair.defaultProperties.getProperty(key);
}
}
}
return value;
}
/**
* Get all messages.
*/
public Map<String, String> getMessages(String language) {
Properties messages = new Properties();
// load properties sequentially
// (default,custom,default language,custom language)
PropertiesPair pair = this.messages.get(null);
if (pair != null) {
messages.putAll(pair.defaultProperties);
messages.putAll(pair.customProperties);
}
if (language != null) {
language = language.toLowerCase();
pair = this.messages.get(language);
if (pair != null) {
messages.putAll(pair.defaultProperties);
messages.putAll(pair.customProperties);
}
}
Map<String, String> result = new HashMap<String, String>();
for(Object key : messages.keySet()) {
result.put(key.toString(), messages.getProperty(key.toString()));
}
return Collections.unmodifiableMap(result);
}
/**
* Dispose component - clear all maps.
*/
public void dispose() {
Iterator<String> it = messages.keySet().iterator();
while (it.hasNext()) {
String language = it.next();
PropertiesPair pair = messages.get(language);
pair.customProperties.clear();
pair.defaultProperties.clear();
}
messages.clear();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/message/impl/DefaultMessageResource.java | Java | art | 8,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.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<strong>Internal classes, do not use directly!</strong>
<p>Message resource implementation</p>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/message/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.message;
import java.io.File;
import java.util.List;
import org.apache.ftpserver.message.impl.DefaultMessageResource;
/**
* Factory for creating message resource implementation
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class MessageResourceFactory {
private List<String> languages;
private File customMessageDirectory;
/**
* Create an {@link MessageResource} based on the configuration on this factory
* @return The {@link MessageResource} instance
*/
public MessageResource createMessageResource() {
return new DefaultMessageResource(languages, customMessageDirectory);
}
/**
* The languages for which messages are available
* @return The list of available languages
*/
public List<String> getLanguages() {
return languages;
}
/**
* Set the languages for which messages are available
* @param languages The list of available languages
*/
public void setLanguages(List<String> languages) {
this.languages = languages;
}
/**
* The directory where custom message bundles can be located
* @return The {@link File} denoting the directory with message bundles
*/
public File getCustomMessageDirectory() {
return customMessageDirectory;
}
/**
* Set the directory where custom message bundles can be located
* @param customMessageDirectory The {@link File} denoting the directory with message bundles
*/
public void setCustomMessageDirectory(File customMessageDirectory) {
this.customMessageDirectory = customMessageDirectory;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/message/MessageResourceFactory.java | Java | art | 2,506 |
/*
* 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.message;
import java.util.List;
import java.util.Map;
/**
* This is message resource interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface MessageResource {
/**
* Get all the available languages.
* @return A list of available languages
*/
List<String> getAvailableLanguages();
/**
* Get the message for the corresponding code and sub id. If not found it
* will return null.
* @param code The reply code
* @param subId The sub ID
* @param language The language
* @return The message matching the provided inputs, or null if not found
*/
String getMessage(int code, String subId, String language);
/**
* Get all the messages.
* @param language The language
* @return All messages for the provided language
*/
Map<String, String> getMessages(String language);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/message/MessageResource.java | Java | art | 1,745 |
/*
* 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.usermanager;
/**
* Password encryptor that does no encryption, that is, keps the
* password in clear text
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ClearTextPasswordEncryptor implements PasswordEncryptor {
/**
* Returns the clear text password
*/
public String encrypt(String password) {
return password;
}
/**
* {@inheritDoc}
*/
public boolean matches(String passwordToCheck, String storedPassword) {
if(storedPassword == null) {
throw new NullPointerException("storedPassword can not be null");
}
if(passwordToCheck == null) {
throw new NullPointerException("passwordToCheck can not be null");
}
return passwordToCheck.equals(storedPassword);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/ClearTextPasswordEncryptor.java | Java | art | 1,666 |
/*
* 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.usermanager;
import java.security.SecureRandom;
import org.apache.ftpserver.util.EncryptUtils;
/**
* Password encryptor that hashes a salt together with the password using MD5.
* Using a salt protects against birthday attacks.
* The hashing is also made in iterations, making lookup attacks much harder.
*
* The algorithm is based on the principles described in
* http://www.jasypt.org/howtoencryptuserpasswords.html
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SaltedPasswordEncryptor implements PasswordEncryptor {
private SecureRandom rnd = new SecureRandom();
private static final int MAX_SEED = 99999999;
private static final int HASH_ITERATIONS = 1000;
private String encrypt(String password, String salt) {
String hash = salt + password;
for (int i = 0; i < HASH_ITERATIONS; i++) {
hash = EncryptUtils.encryptMD5(hash);
}
return salt + ":" + hash;
}
/**
* Encrypts the password using a salt concatenated with the password
* and a series of MD5 steps.
*/
public String encrypt(String password) {
String seed = Integer.toString(rnd.nextInt(MAX_SEED));
return encrypt(password, seed);
}
/**
* {@inheritDoc}
*/
public boolean matches(String passwordToCheck, String storedPassword) {
if (storedPassword == null) {
throw new NullPointerException("storedPassword can not be null");
}
if (passwordToCheck == null) {
throw new NullPointerException("passwordToCheck can not be null");
}
// look for divider for hash
int divider = storedPassword.indexOf(':');
if(divider < 1) {
throw new IllegalArgumentException("stored password does not contain salt");
}
String storedSalt = storedPassword.substring(0, divider);
return encrypt(passwordToCheck, storedSalt).equalsIgnoreCase(storedPassword);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/SaltedPasswordEncryptor.java | Java | art | 2,866 |
/*
* 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.usermanager;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.usermanager.impl.UserMetadata;
/**
* Class representing an anonymous authentication attempt
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class AnonymousAuthentication implements Authentication {
private UserMetadata userMetadata;
/**
* Default constructor
*/
public AnonymousAuthentication() {
// empty
}
/**
* Constructor with an additional user metadata parameter
*
* @param userMetadata
* User metadata
*/
public AnonymousAuthentication(UserMetadata userMetadata) {
this.userMetadata = userMetadata;
}
/**
* Retrive the user metadata
*
* @return The user metadata
*/
public UserMetadata getUserMetadata() {
return userMetadata;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/AnonymousAuthentication.java | Java | art | 1,741 |
/*
* 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.usermanager;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.usermanager.impl.UserMetadata;
/**
* Class representing a normal authentication attempt using username and
* password
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class UsernamePasswordAuthentication implements Authentication {
private String username;
private String password;
private UserMetadata userMetadata;
/**
* Constructor with the minimal data for an authentication
*
* @param username
* The user name
* @param password
* The password, can be null
*/
public UsernamePasswordAuthentication(final String username,
final String password) {
this.username = username;
this.password = password;
}
/**
* Constructor with an additonal parameter for user metadata
*
* @param username
* The user name
* @param password
* The password, can be null
* @param userMetadata
* The user metadata
*/
public UsernamePasswordAuthentication(final String username,
final String password, final UserMetadata userMetadata) {
this(username, password);
this.userMetadata = userMetadata;
}
/**
* Retrive the password
*
* @return The password
*/
public String getPassword() {
return password;
}
/**
* Retrive the user name
*
* @return The user name
*/
public String getUsername() {
return username;
}
/**
* Retrive the user metadata
*
* @return The user metadata
*/
public UserMetadata getUserMetadata() {
return userMetadata;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/UsernamePasswordAuthentication.java | Java | art | 2,642 |
/*
* 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.usermanager;
import javax.sql.DataSource;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.impl.DbUserManager;
/**
* Factory for database backed {@link UserManager} instances.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DbUserManagerFactory implements UserManagerFactory {
private String adminName = "admin";
private String insertUserStmt;
private String updateUserStmt;
private String deleteUserStmt;
private String selectUserStmt;
private String selectAllStmt;
private String isAdminStmt;
private String authenticateStmt;
private DataSource dataSource;
private PasswordEncryptor passwordEncryptor = new Md5PasswordEncryptor();
public UserManager createUserManager() {
if (dataSource == null) {
throw new FtpServerConfigurationException(
"Required data source not provided");
}
if (insertUserStmt == null) {
throw new FtpServerConfigurationException(
"Required insert user SQL statement not provided");
}
if (updateUserStmt == null) {
throw new FtpServerConfigurationException(
"Required update user SQL statement not provided");
}
if (deleteUserStmt == null) {
throw new FtpServerConfigurationException(
"Required delete user SQL statement not provided");
}
if (selectUserStmt == null) {
throw new FtpServerConfigurationException(
"Required select user SQL statement not provided");
}
if (selectAllStmt == null) {
throw new FtpServerConfigurationException(
"Required select all users SQL statement not provided");
}
if (isAdminStmt == null) {
throw new FtpServerConfigurationException(
"Required is admin user SQL statement not provided");
}
if (authenticateStmt == null) {
throw new FtpServerConfigurationException(
"Required authenticate user SQL statement not provided");
}
return new DbUserManager(dataSource, selectAllStmt, selectUserStmt,
insertUserStmt, updateUserStmt, deleteUserStmt, authenticateStmt,
isAdminStmt, passwordEncryptor, adminName);
}
/**
* Get the admin name.
* @return The admin user name
*/
public String getAdminName() {
return adminName;
}
/**
* Set the name to use as the administrator of the server. The default value
* is "admin".
*
* @param adminName
* The administrator user name
*/
public void setAdminName(String adminName) {
this.adminName = adminName;
}
/**
* Retrive the data source used by the user manager
*
* @return The current data source
*/
public DataSource getDataSource() {
return dataSource;
}
/**
* Set the data source to be used by the user manager
*
* @param dataSource
* The data source to use
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Get the SQL INSERT statement used to add a new user.
*
* @return The SQL statement
*/
public String getSqlUserInsert() {
return insertUserStmt;
}
/**
* Set the SQL INSERT statement used to add a new user. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserInsert(String sql) {
insertUserStmt = sql;
}
/**
* Get the SQL DELETE statement used to delete an existing user.
*
* @return The SQL statement
*/
public String getSqlUserDelete() {
return deleteUserStmt;
}
/**
* Set the SQL DELETE statement used to delete an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserDelete(String sql) {
deleteUserStmt = sql;
}
/**
* Get the SQL UPDATE statement used to update an existing user.
*
* @return The SQL statement
*/
public String getSqlUserUpdate() {
return updateUserStmt;
}
/**
* Set the SQL UPDATE statement used to update an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserUpdate(String sql) {
updateUserStmt = sql;
}
/**
* Get the SQL SELECT statement used to select an existing user.
*
* @return The SQL statement
*/
public String getSqlUserSelect() {
return selectUserStmt;
}
/**
* Set the SQL SELECT statement used to select an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserSelect(String sql) {
selectUserStmt = sql;
}
/**
* Get the SQL SELECT statement used to select all user ids.
*
* @return The SQL statement
*/
public String getSqlUserSelectAll() {
return selectAllStmt;
}
/**
* Set the SQL SELECT statement used to select all user ids. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserSelectAll(String sql) {
selectAllStmt = sql;
}
/**
* Get the SQL SELECT statement used to authenticate user.
*
* @return The SQL statement
*/
public String getSqlUserAuthenticate() {
return authenticateStmt;
}
/**
* Set the SQL SELECT statement used to authenticate user. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserAuthenticate(String sql) {
authenticateStmt = sql;
}
/**
* Get the SQL SELECT statement used to find whether an user is admin or
* not.
*
* @return The SQL statement
*/
public String getSqlUserAdmin() {
return isAdminStmt;
}
/**
* Set the SQL SELECT statement used to find whether an user is admin or
* not. All the dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserAdmin(String sql) {
isAdminStmt = sql;
}
/**
* Retrieve the password encryptor used for this user manager
* @return The password encryptor. Default to {@link Md5PasswordEncryptor}
* if no other has been provided
*/
public PasswordEncryptor getPasswordEncryptor() {
return passwordEncryptor;
}
/**
* Set the password encryptor to use for this user manager
* @param passwordEncryptor The password encryptor
*/
public void setPasswordEncryptor(PasswordEncryptor passwordEncryptor) {
this.passwordEncryptor = passwordEncryptor;
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/DbUserManagerFactory.java | Java | art | 8,282 |
/*
* 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.usermanager;
/**
* Strategy used for encrypting and matching encrypted passwords.
* The purpose is to make the password encryption possible to extend.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface PasswordEncryptor {
/**
* Encrypts the password
* @param password The clear text password
* @return The encrypted password
*/
String encrypt(String password);
/**
* Matches an encrypted password with that stored
* @param passwordToCheck The encrypted password to check
* @param storedPassword The stored password
* @return true if the password match
*/
boolean matches(String passwordToCheck, String storedPassword);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/PasswordEncryptor.java | Java | art | 1,572 |
/*
* 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.usermanager;
import org.apache.ftpserver.util.EncryptUtils;
/**
* Password encryptor that hashes the password using MD5. Please note that this form
* of encryption is sensitive to lookup attacks.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class Md5PasswordEncryptor implements PasswordEncryptor {
/**
* Hashes the password using MD5
*/
public String encrypt(String password) {
return EncryptUtils.encryptMD5(password);
}
/**
* {@inheritDoc}
*/
public boolean matches(String passwordToCheck, String storedPassword) {
if(storedPassword == null) {
throw new NullPointerException("storedPassword can not be null");
}
if(passwordToCheck == null) {
throw new NullPointerException("passwordToCheck can not be null");
}
return encrypt(passwordToCheck).equalsIgnoreCase(storedPassword);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/Md5PasswordEncryptor.java | Java | art | 1,793 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Class representing a request to log in a number of concurrent times
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ConcurrentLoginRequest implements AuthorizationRequest {
private int concurrentLogins;
private int concurrentLoginsFromThisIP;
private int maxConcurrentLogins = 0;
private int maxConcurrentLoginsPerIP = 0;
/**
* @param concurrentLogins
* @param concurrentLoginsFromThisIP
*/
public ConcurrentLoginRequest(int concurrentLogins,
int concurrentLoginsFromThisIP) {
super();
this.concurrentLogins = concurrentLogins;
this.concurrentLoginsFromThisIP = concurrentLoginsFromThisIP;
}
/**
* The number of concurrent logins requested
*
* @return the concurrentLogins The number of current concurrent logins
*/
public int getConcurrentLogins() {
return concurrentLogins;
}
/**
* The number of concurrent logins from this IP requested
*
* @return the concurrentLoginsFromThisIP The number of current concurrent
* logins from this IP
*/
public int getConcurrentLoginsFromThisIP() {
return concurrentLoginsFromThisIP;
}
/**
* The maximum allowed concurrent logins for this user, or 0 if no limit is
* set. This is normally populated by {@link ConcurrentLoginPermission}
*
* @return The maximum allowed concurrent logins
*/
public int getMaxConcurrentLogins() {
return maxConcurrentLogins;
}
/**
* Set the maximum allowed concurrent logins for this user
*
* @param maxConcurrentLogins
* Set max allowed concurrent connections
*/
void setMaxConcurrentLogins(int maxConcurrentLogins) {
this.maxConcurrentLogins = maxConcurrentLogins;
}
/**
* The maximum allowed concurrent logins per IP for this user, or 0 if no
* limit is set. This is normally populated by
* {@link ConcurrentLoginPermission}
*
* @return The maximum allowed concurrent logins per IP
*/
public int getMaxConcurrentLoginsPerIP() {
return maxConcurrentLoginsPerIP;
}
/**
* Set the maximum allowed concurrent logins per IP for this user
*
* @param maxConcurrentLoginsPerIP
* Set max allowed concurrent connections per IP
*/
void setMaxConcurrentLoginsPerIP(int maxConcurrentLoginsPerIP) {
this.maxConcurrentLoginsPerIP = maxConcurrentLoginsPerIP;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/ConcurrentLoginRequest.java | Java | art | 3,533 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Class representing a write permission
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class WritePermission implements Authority {
private String permissionRoot;
/**
* Construct a write permission for the user home directory (/)
*/
public WritePermission() {
this.permissionRoot = "/";
}
/**
* Construct a write permission for a file or directory relative to the user
* home directory
*
* @param permissionRoot
* The file or directory
*/
public WritePermission(final String permissionRoot) {
this.permissionRoot = permissionRoot;
}
/**
* @see Authority#authorize(AuthorizationRequest)
*/
public AuthorizationRequest authorize(final AuthorizationRequest request) {
if (request instanceof WriteRequest) {
WriteRequest writeRequest = (WriteRequest) request;
String requestFile = writeRequest.getFile();
if (requestFile.startsWith(permissionRoot)) {
return writeRequest;
} else {
return null;
}
} else {
return null;
}
}
/**
* @see Authority#canAuthorize(AuthorizationRequest)
*/
public boolean canAuthorize(final AuthorizationRequest request) {
return request instanceof WriteRequest;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/WritePermission.java | Java | art | 2,432 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Request for getting the maximum allowed transfer rates for a user
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TransferRateRequest implements AuthorizationRequest {
private int maxDownloadRate = 0;
private int maxUploadRate = 0;
/**
* @return the maxDownloadRate
*/
public int getMaxDownloadRate() {
return maxDownloadRate;
}
/**
* @param maxDownloadRate
* the maxDownloadRate to set
*/
public void setMaxDownloadRate(int maxDownloadRate) {
this.maxDownloadRate = maxDownloadRate;
}
/**
* @return the maxUploadRate
*/
public int getMaxUploadRate() {
return maxUploadRate;
}
/**
* @param maxUploadRate
* the maxUploadRate to set
*/
public void setMaxUploadRate(int maxUploadRate) {
this.maxUploadRate = maxUploadRate;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/TransferRateRequest.java | Java | art | 1,913 |
/*
* 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.usermanager.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.AnonymousAuthentication;
import org.apache.ftpserver.usermanager.PasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.UsernamePasswordAuthentication;
import org.apache.ftpserver.util.BaseProperties;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* <p>Properties file based <code>UserManager</code> implementation. We use
* <code>user.properties</code> file to store user data.</p>
*
* </p>The file will use the following properties for storing users:</p>
* <table>
* <tr>
* <th>Property</th>
* <th>Documentation</th>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.homedirectory</td>
* <td>Path to the home directory for the user, based on the file system implementation used</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.userpassword</td>
* <td>The password for the user. Can be in clear text, MD5 hash or salted SHA hash based on the
* configuration on the user manager
* </td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.enableflag</td>
* <td>true if the user is enabled, false otherwise</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.writepermission</td>
* <td>true if the user is allowed to upload files and create directories, false otherwise</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.idletime</td>
* <td>The number of seconds the user is allowed to be idle before disconnected.
* 0 disables the idle timeout
* </td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.maxloginnumber</td>
* <td>The maximum number of concurrent logins by the user. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.maxloginperip</td>
* <td>The maximum number of concurrent logins from the same IP address by the user. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.uploadrate</td>
* <td>The maximum number of bytes per second the user is allowed to upload files. 0 disables the check.</td>
* </tr>
* <tr>
* <td>ftpserver.user.{username}.downloadrate</td>
* <td>The maximum number of bytes per second the user is allowed to download files. 0 disables the check.</td>
* </tr>
* </table>
*
* <p>Example:</p>
* <pre>
* ftpserver.user.admin.homedirectory=/ftproot
* ftpserver.user.admin.userpassword=admin
* ftpserver.user.admin.enableflag=true
* ftpserver.user.admin.writepermission=true
* ftpserver.user.admin.idletime=0
* ftpserver.user.admin.maxloginnumber=0
* ftpserver.user.admin.maxloginperip=0
* ftpserver.user.admin.uploadrate=0
* ftpserver.user.admin.downloadrate=0
* </pre>
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PropertiesUserManager extends AbstractUserManager {
private final Logger LOG = LoggerFactory
.getLogger(PropertiesUserManager.class);
private final static String PREFIX = "ftpserver.user.";
private BaseProperties userDataProp;
private File userDataFile;
private URL userUrl;
/**
* Internal constructor, do not use directly. Use {@link PropertiesUserManagerFactory} instead.
*/
public PropertiesUserManager(PasswordEncryptor passwordEncryptor,
File userDataFile, String adminName) {
super(adminName, passwordEncryptor);
loadFromFile(userDataFile);
}
/**
* Internal constructor, do not use directly. Use {@link PropertiesUserManagerFactory} instead.
*/
public PropertiesUserManager(PasswordEncryptor passwordEncryptor,
URL userDataPath, String adminName) {
super(adminName, passwordEncryptor);
loadFromUrl(userDataPath);
}
private void loadFromFile(File userDataFile) {
try {
userDataProp = new BaseProperties();
if (userDataFile != null) {
LOG.debug("File configured, will try loading");
if (userDataFile.exists()) {
this.userDataFile = userDataFile;
LOG.debug("File found on file system");
FileInputStream fis = null;
try {
fis = new FileInputStream(userDataFile);
userDataProp.load(fis);
} finally {
IoUtils.close(fis);
}
} else {
// try loading it from the classpath
LOG
.debug("File not found on file system, try loading from classpath");
InputStream is = getClass().getClassLoader()
.getResourceAsStream(userDataFile.getPath());
if (is != null) {
try {
userDataProp.load(is);
} finally {
IoUtils.close(is);
}
} else {
throw new FtpServerConfigurationException(
"User data file specified but could not be located, "
+ "neither on the file system or in the classpath: "
+ userDataFile.getPath());
}
}
}
} catch (IOException e) {
throw new FtpServerConfigurationException(
"Error loading user data file : " + userDataFile, e);
}
}
private void loadFromUrl(URL userDataPath) {
try {
userDataProp = new BaseProperties();
if (userDataPath != null) {
LOG.debug("URL configured, will try loading");
userUrl = userDataPath;
InputStream is = null;
is = userDataPath.openStream();
try {
userDataProp.load(is);
} finally {
IoUtils.close(is);
}
}
} catch (IOException e) {
throw new FtpServerConfigurationException(
"Error loading user data resource : " + userDataPath, e);
}
}
/**
* Reloads the contents of the user.properties file. This allows any manual modifications to the file to be recognised by the running server.
*/
public void refresh() {
synchronized (userDataProp) {
if (userDataFile != null) {
LOG.debug("Refreshing user manager using file: "
+ userDataFile.getAbsolutePath());
loadFromFile(userDataFile);
} else {
//file is null, must have been created using URL
LOG.debug("Refreshing user manager using URL: "
+ userUrl.toString());
loadFromUrl(userUrl);
}
}
}
/**
* Retrive the file backing this user manager
* @return The file
*/
public File getFile() {
return userDataFile;
}
/**
* Save user data. Store the properties.
*/
public synchronized void save(User usr) throws FtpException {
// null value check
if (usr.getName() == null) {
throw new NullPointerException("User name is null.");
}
String thisPrefix = PREFIX + usr.getName() + '.';
// set other properties
userDataProp.setProperty(thisPrefix + ATTR_PASSWORD, getPassword(usr));
String home = usr.getHomeDirectory();
if (home == null) {
home = "/";
}
userDataProp.setProperty(thisPrefix + ATTR_HOME, home);
userDataProp.setProperty(thisPrefix + ATTR_ENABLE, usr.getEnabled());
userDataProp.setProperty(thisPrefix + ATTR_WRITE_PERM, usr
.authorize(new WriteRequest()) != null);
userDataProp.setProperty(thisPrefix + ATTR_MAX_IDLE_TIME, usr
.getMaxIdleTime());
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) usr
.authorize(transferRateRequest);
if (transferRateRequest != null) {
userDataProp.setProperty(thisPrefix + ATTR_MAX_UPLOAD_RATE,
transferRateRequest.getMaxUploadRate());
userDataProp.setProperty(thisPrefix + ATTR_MAX_DOWNLOAD_RATE,
transferRateRequest.getMaxDownloadRate());
} else {
userDataProp.remove(thisPrefix + ATTR_MAX_UPLOAD_RATE);
userDataProp.remove(thisPrefix + ATTR_MAX_DOWNLOAD_RATE);
}
// request that always will succeed
ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(
0, 0);
concurrentLoginRequest = (ConcurrentLoginRequest) usr
.authorize(concurrentLoginRequest);
if (concurrentLoginRequest != null) {
userDataProp.setProperty(thisPrefix + ATTR_MAX_LOGIN_NUMBER,
concurrentLoginRequest.getMaxConcurrentLogins());
userDataProp.setProperty(thisPrefix + ATTR_MAX_LOGIN_PER_IP,
concurrentLoginRequest.getMaxConcurrentLoginsPerIP());
} else {
userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_NUMBER);
userDataProp.remove(thisPrefix + ATTR_MAX_LOGIN_PER_IP);
}
saveUserData();
}
/**
* @throws FtpException
*/
private void saveUserData() throws FtpException {
if (userDataFile == null) {
return;
}
File dir = userDataFile.getAbsoluteFile().getParentFile();
if (dir != null && !dir.exists() && !dir.mkdirs()) {
String dirName = dir.getAbsolutePath();
throw new FtpServerConfigurationException(
"Cannot create directory for user data file : " + dirName);
}
// save user data
FileOutputStream fos = null;
try {
fos = new FileOutputStream(userDataFile);
userDataProp.store(fos, "Generated file - don't edit (please)");
} catch (IOException ex) {
LOG.error("Failed saving user data", ex);
throw new FtpException("Failed saving user data", ex);
} finally {
IoUtils.close(fos);
}
}
/**
* Delete an user. Removes all this user entries from the properties. After
* removing the corresponding from the properties, save the data.
*/
public void delete(String usrName) throws FtpException {
// remove entries from properties
String thisPrefix = PREFIX + usrName + '.';
Enumeration<?> propNames = userDataProp.propertyNames();
ArrayList<String> remKeys = new ArrayList<String>();
while (propNames.hasMoreElements()) {
String thisKey = propNames.nextElement().toString();
if (thisKey.startsWith(thisPrefix)) {
remKeys.add(thisKey);
}
}
Iterator<String> remKeysIt = remKeys.iterator();
while (remKeysIt.hasNext()) {
userDataProp.remove(remKeysIt.next());
}
saveUserData();
}
/**
* Get user password. Returns the encrypted value.
*
* <pre>
* If the password value is not null
* password = new password
* else
* if user does exist
* password = old password
* else
* password = ""
* </pre>
*/
private String getPassword(User usr) {
String name = usr.getName();
String password = usr.getPassword();
if (password != null) {
password = getPasswordEncryptor().encrypt(password);
} else {
String blankPassword = getPasswordEncryptor().encrypt("");
if (doesExist(name)) {
String key = PREFIX + name + '.' + ATTR_PASSWORD;
password = userDataProp.getProperty(key, blankPassword);
} else {
password = blankPassword;
}
}
return password;
}
/**
* Get all user names.
*/
public String[] getAllUserNames() {
// get all user names
String suffix = '.' + ATTR_HOME;
ArrayList<String> ulst = new ArrayList<String>();
Enumeration<?> allKeys = userDataProp.propertyNames();
int prefixlen = PREFIX.length();
int suffixlen = suffix.length();
while (allKeys.hasMoreElements()) {
String key = (String) allKeys.nextElement();
if (key.endsWith(suffix)) {
String name = key.substring(prefixlen);
int endIndex = name.length() - suffixlen;
name = name.substring(0, endIndex);
ulst.add(name);
}
}
Collections.sort(ulst);
return ulst.toArray(new String[0]);
}
/**
* Load user data.
*/
public User getUserByName(String userName) {
if (!doesExist(userName)) {
return null;
}
String baseKey = PREFIX + userName + '.';
BaseUser user = new BaseUser();
user.setName(userName);
user.setEnabled(userDataProp.getBoolean(baseKey + ATTR_ENABLE, true));
user.setHomeDirectory(userDataProp
.getProperty(baseKey + ATTR_HOME, "/"));
List<Authority> authorities = new ArrayList<Authority>();
if (userDataProp.getBoolean(baseKey + ATTR_WRITE_PERM, false)) {
authorities.add(new WritePermission());
}
int maxLogin = userDataProp.getInteger(baseKey + ATTR_MAX_LOGIN_NUMBER,
0);
int maxLoginPerIP = userDataProp.getInteger(baseKey
+ ATTR_MAX_LOGIN_PER_IP, 0);
authorities.add(new ConcurrentLoginPermission(maxLogin, maxLoginPerIP));
int uploadRate = userDataProp.getInteger(
baseKey + ATTR_MAX_UPLOAD_RATE, 0);
int downloadRate = userDataProp.getInteger(baseKey
+ ATTR_MAX_DOWNLOAD_RATE, 0);
authorities.add(new TransferRatePermission(downloadRate, uploadRate));
user.setAuthorities(authorities);
user.setMaxIdleTime(userDataProp.getInteger(baseKey
+ ATTR_MAX_IDLE_TIME, 0));
return user;
}
/**
* User existance check
*/
public boolean doesExist(String name) {
String key = PREFIX + name + '.' + ATTR_HOME;
return userDataProp.containsKey(key);
}
/**
* User authenticate method
*/
public User authenticate(Authentication authentication)
throws AuthenticationFailedException {
if (authentication instanceof UsernamePasswordAuthentication) {
UsernamePasswordAuthentication upauth = (UsernamePasswordAuthentication) authentication;
String user = upauth.getUsername();
String password = upauth.getPassword();
if (user == null) {
throw new AuthenticationFailedException("Authentication failed");
}
if (password == null) {
password = "";
}
String storedPassword = userDataProp.getProperty(PREFIX + user
+ '.' + ATTR_PASSWORD);
if (storedPassword == null) {
// user does not exist
throw new AuthenticationFailedException("Authentication failed");
}
if (getPasswordEncryptor().matches(password, storedPassword)) {
return getUserByName(user);
} else {
throw new AuthenticationFailedException("Authentication failed");
}
} else if (authentication instanceof AnonymousAuthentication) {
if (doesExist("anonymous")) {
return getUserByName("anonymous");
} else {
throw new AuthenticationFailedException("Authentication failed");
}
} else {
throw new IllegalArgumentException(
"Authentication not supported by this user manager");
}
}
/**
* Close the user manager - remove existing entries.
*/
public synchronized void dispose() {
if (userDataProp != null) {
userDataProp.clear();
userDataProp = null;
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/PropertiesUserManager.java | Java | art | 18,110 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The max upload rate permission
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class ConcurrentLoginPermission implements Authority {
private int maxConcurrentLogins;
private int maxConcurrentLoginsPerIP;
public ConcurrentLoginPermission(int maxConcurrentLogins,
int maxConcurrentLoginsPerIP) {
this.maxConcurrentLogins = maxConcurrentLogins;
this.maxConcurrentLoginsPerIP = maxConcurrentLoginsPerIP;
}
/**
* @see Authority#authorize(AuthorizationRequest)
*/
public AuthorizationRequest authorize(AuthorizationRequest request) {
if (request instanceof ConcurrentLoginRequest) {
ConcurrentLoginRequest concurrentLoginRequest = (ConcurrentLoginRequest) request;
if (maxConcurrentLogins != 0
&& maxConcurrentLogins < concurrentLoginRequest
.getConcurrentLogins()) {
return null;
} else if (maxConcurrentLoginsPerIP != 0
&& maxConcurrentLoginsPerIP < concurrentLoginRequest
.getConcurrentLoginsFromThisIP()) {
return null;
} else {
concurrentLoginRequest
.setMaxConcurrentLogins(maxConcurrentLogins);
concurrentLoginRequest
.setMaxConcurrentLoginsPerIP(maxConcurrentLoginsPerIP);
return concurrentLoginRequest;
}
} else {
return null;
}
}
/**
* @see Authority#canAuthorize(AuthorizationRequest)
*/
public boolean canAuthorize(AuthorizationRequest request) {
return request instanceof ConcurrentLoginRequest;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/ConcurrentLoginPermission.java | Java | art | 2,793 |
/*
* 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.usermanager.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.sql.DataSource;
import org.apache.ftpserver.FtpServerConfigurationException;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.AnonymousAuthentication;
import org.apache.ftpserver.usermanager.DbUserManagerFactory;
import org.apache.ftpserver.usermanager.PasswordEncryptor;
import org.apache.ftpserver.usermanager.UsernamePasswordAuthentication;
import org.apache.ftpserver.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is another database based user manager class. It has been tested in
* MySQL and Oracle 8i database. The schema file is </code>res/ftp-db.sql</code>
*
* All the user attributes are replaced during run-time. So we can use your
* database schema. Then you need to modify the SQLs in the configuration file.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DbUserManager extends AbstractUserManager {
private final Logger LOG = LoggerFactory.getLogger(DbUserManager.class);
private String insertUserStmt;
private String updateUserStmt;
private String deleteUserStmt;
private String selectUserStmt;
private String selectAllStmt;
private String isAdminStmt;
private String authenticateStmt;
private DataSource dataSource;
/**
* Internal constructor, do not use directly. Use {@link DbUserManagerFactory} instead.
*/
public DbUserManager(DataSource dataSource, String selectAllStmt,
String selectUserStmt, String insertUserStmt,
String updateUserStmt, String deleteUserStmt,
String authenticateStmt, String isAdminStmt,
PasswordEncryptor passwordEncryptor, String adminName) {
super(adminName, passwordEncryptor);
this.dataSource = dataSource;
this.selectAllStmt = selectAllStmt;
this.selectUserStmt = selectUserStmt;
this.insertUserStmt = insertUserStmt;
this.updateUserStmt = updateUserStmt;
this.deleteUserStmt = deleteUserStmt;
this.authenticateStmt = authenticateStmt;
this.isAdminStmt = isAdminStmt;
Connection con = null;
try {
// test the connection
con = createConnection();
LOG.info("Database connection opened.");
} catch (SQLException ex) {
LOG.error("Failed to open connection to user database", ex);
throw new FtpServerConfigurationException(
"Failed to open connection to user database", ex);
} finally{
closeQuitely(con);
}
}
/**
* Retrive the data source used by the user manager
*
* @return The current data source
*/
public DataSource getDataSource() {
return dataSource;
}
/**
* Set the data source to be used by the user manager
*
* @param dataSource
* The data source to use
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Get the SQL INSERT statement used to add a new user.
*
* @return The SQL statement
*/
public String getSqlUserInsert() {
return insertUserStmt;
}
/**
* Set the SQL INSERT statement used to add a new user. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserInsert(String sql) {
insertUserStmt = sql;
}
/**
* Get the SQL DELETE statement used to delete an existing user.
*
* @return The SQL statement
*/
public String getSqlUserDelete() {
return deleteUserStmt;
}
/**
* Set the SQL DELETE statement used to delete an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserDelete(String sql) {
deleteUserStmt = sql;
}
/**
* Get the SQL UPDATE statement used to update an existing user.
*
* @return The SQL statement
*/
public String getSqlUserUpdate() {
return updateUserStmt;
}
/**
* Set the SQL UPDATE statement used to update an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserUpdate(String sql) {
updateUserStmt = sql;
}
/**
* Get the SQL SELECT statement used to select an existing user.
*
* @return The SQL statement
*/
public String getSqlUserSelect() {
return selectUserStmt;
}
/**
* Set the SQL SELECT statement used to select an existing user. All the
* dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserSelect(String sql) {
selectUserStmt = sql;
}
/**
* Get the SQL SELECT statement used to select all user ids.
*
* @return The SQL statement
*/
public String getSqlUserSelectAll() {
return selectAllStmt;
}
/**
* Set the SQL SELECT statement used to select all user ids. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserSelectAll(String sql) {
selectAllStmt = sql;
}
/**
* Get the SQL SELECT statement used to authenticate user.
*
* @return The SQL statement
*/
public String getSqlUserAuthenticate() {
return authenticateStmt;
}
/**
* Set the SQL SELECT statement used to authenticate user. All the dynamic
* values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserAuthenticate(String sql) {
authenticateStmt = sql;
}
/**
* Get the SQL SELECT statement used to find whether an user is admin or
* not.
*
* @return The SQL statement
*/
public String getSqlUserAdmin() {
return isAdminStmt;
}
/**
* Set the SQL SELECT statement used to find whether an user is admin or
* not. All the dynamic values will be replaced during runtime.
*
* @param sql
* The SQL statement
*/
public void setSqlUserAdmin(String sql) {
isAdminStmt = sql;
}
/**
* @return true if user with this login is administrator
*/
public boolean isAdmin(String login) throws FtpException {
// check input
if (login == null) {
return false;
}
Statement stmt = null;
ResultSet rs = null;
try {
// create the sql query
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(login));
String sql = StringUtils.replaceString(isAdminStmt, map);
LOG.info(sql);
// execute query
stmt = createConnection().createStatement();
rs = stmt.executeQuery(sql);
return rs.next();
} catch (SQLException ex) {
LOG.error("DbUserManager.isAdmin()", ex);
throw new FtpException("DbUserManager.isAdmin()", ex);
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
}
/**
* Open connection to database.
*/
protected Connection createConnection() throws SQLException {
Connection connection = dataSource.getConnection();
connection.setAutoCommit(true);
return connection;
}
/**
* Delete user. Delete the row from the table.
*/
public void delete(String name) throws FtpException {
// create sql query
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(name));
String sql = StringUtils.replaceString(deleteUserStmt, map);
LOG.info(sql);
// execute query
Statement stmt = null;
try {
stmt = createConnection().createStatement();
stmt.executeUpdate(sql);
} catch (SQLException ex) {
LOG.error("DbUserManager.delete()", ex);
throw new FtpException("DbUserManager.delete()", ex);
} finally {
closeQuitely(stmt);
}
}
/**
* Save user. If new insert a new row, else update the existing row.
*/
public void save(User user) throws FtpException {
// null value check
if (user.getName() == null) {
throw new NullPointerException("User name is null.");
}
Statement stmt = null;
try {
// create sql query
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(user.getName()));
String password = null;
if(user.getPassword() != null) {
// password provided, encrypt it and store the encrypted value
password= getPasswordEncryptor().encrypt(user.getPassword());
} else {
// password was not provided, either load from the existing user and store that again
// or store as null
ResultSet rs = null;
try {
User userWithPassword = selectUserByName(user.getName());
if(userWithPassword != null) {
// user exists, reuse password
password = userWithPassword.getPassword();
}
} finally {
closeQuitely(rs);
}
}
map.put(ATTR_PASSWORD, escapeString(password));
String home = user.getHomeDirectory();
if (home == null) {
home = "/";
}
map.put(ATTR_HOME, escapeString(home));
map.put(ATTR_ENABLE, String.valueOf(user.getEnabled()));
map.put(ATTR_WRITE_PERM, String.valueOf(user
.authorize(new WriteRequest()) != null));
map.put(ATTR_MAX_IDLE_TIME, user.getMaxIdleTime());
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) user
.authorize(transferRateRequest);
if (transferRateRequest != null) {
map.put(ATTR_MAX_UPLOAD_RATE, transferRateRequest
.getMaxUploadRate());
map.put(ATTR_MAX_DOWNLOAD_RATE, transferRateRequest
.getMaxDownloadRate());
} else {
map.put(ATTR_MAX_UPLOAD_RATE, 0);
map.put(ATTR_MAX_DOWNLOAD_RATE, 0);
}
// request that always will succeed
ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(
0, 0);
concurrentLoginRequest = (ConcurrentLoginRequest) user
.authorize(concurrentLoginRequest);
if (concurrentLoginRequest != null) {
map.put(ATTR_MAX_LOGIN_NUMBER, concurrentLoginRequest
.getMaxConcurrentLogins());
map.put(ATTR_MAX_LOGIN_PER_IP, concurrentLoginRequest
.getMaxConcurrentLoginsPerIP());
} else {
map.put(ATTR_MAX_LOGIN_NUMBER, 0);
map.put(ATTR_MAX_LOGIN_PER_IP, 0);
}
String sql = null;
if (!doesExist(user.getName())) {
sql = StringUtils.replaceString(insertUserStmt, map);
} else {
sql = StringUtils.replaceString(updateUserStmt, map);
}
LOG.info(sql);
// execute query
stmt = createConnection().createStatement();
stmt.executeUpdate(sql);
} catch (SQLException ex) {
LOG.error("DbUserManager.save()", ex);
throw new FtpException("DbUserManager.save()", ex);
} finally {
closeQuitely(stmt);
}
}
private void closeQuitely(Statement stmt) {
if(stmt != null) {
Connection con = null;
try {
con = stmt.getConnection();
} catch (Exception e) {
}
try {
stmt.close();
} catch (SQLException e) {
// ignore
}
closeQuitely(con);
}
}
private void closeQuitely(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
// ignore
}
}
}
protected void closeQuitely(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// ignore
}
}
}
private BaseUser selectUserByName(String name) throws SQLException {
// create sql query
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(name));
String sql = StringUtils.replaceString(selectUserStmt, map);
LOG.info(sql);
Statement stmt = null;
ResultSet rs = null;
try {
// execute query
stmt = createConnection().createStatement();
rs = stmt.executeQuery(sql);
// populate user object
BaseUser thisUser = null;
if (rs.next()) {
thisUser = new BaseUser();
thisUser.setName(rs.getString(ATTR_LOGIN));
thisUser.setPassword(rs.getString(ATTR_PASSWORD));
thisUser.setHomeDirectory(rs.getString(ATTR_HOME));
thisUser.setEnabled(rs.getBoolean(ATTR_ENABLE));
thisUser.setMaxIdleTime(rs.getInt(ATTR_MAX_IDLE_TIME));
List<Authority> authorities = new ArrayList<Authority>();
if (rs.getBoolean(ATTR_WRITE_PERM)) {
authorities.add(new WritePermission());
}
authorities.add(new ConcurrentLoginPermission(rs
.getInt(ATTR_MAX_LOGIN_NUMBER), rs
.getInt(ATTR_MAX_LOGIN_PER_IP)));
authorities.add(new TransferRatePermission(rs
.getInt(ATTR_MAX_DOWNLOAD_RATE), rs
.getInt(ATTR_MAX_UPLOAD_RATE)));
thisUser.setAuthorities(authorities);
}
return thisUser;
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
}
/**
* Get the user object. Fetch the row from the table.
*/
public User getUserByName(String name) throws FtpException {
Statement stmt = null;
ResultSet rs = null;
try {
BaseUser user = selectUserByName(name);
if(user != null) {
// reset the password, not to be sent to API users
user.setPassword(null);
}
return user;
} catch (SQLException ex) {
LOG.error("DbUserManager.getUserByName()", ex);
throw new FtpException("DbUserManager.getUserByName()", ex);
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
}
/**
* User existance check.
*/
public boolean doesExist(String name) throws FtpException {
Statement stmt = null;
ResultSet rs = null;
try {
// create the sql
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(name));
String sql = StringUtils.replaceString(selectUserStmt, map);
LOG.info(sql);
// execute query
stmt = createConnection().createStatement();
rs = stmt.executeQuery(sql);
return rs.next();
} catch (SQLException ex) {
LOG.error("DbUserManager.doesExist()", ex);
throw new FtpException("DbUserManager.doesExist()", ex);
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
}
/**
* Get all user names from the database.
*/
public String[] getAllUserNames() throws FtpException {
Statement stmt = null;
ResultSet rs = null;
try {
// create sql query
String sql = selectAllStmt;
LOG.info(sql);
// execute query
stmt = createConnection().createStatement();
rs = stmt.executeQuery(sql);
// populate list
ArrayList<String> names = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(ATTR_LOGIN));
}
return names.toArray(new String[0]);
} catch (SQLException ex) {
LOG.error("DbUserManager.getAllUserNames()", ex);
throw new FtpException("DbUserManager.getAllUserNames()", ex);
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
}
/**
* User authentication.
*/
public User authenticate(Authentication authentication)
throws AuthenticationFailedException {
if (authentication instanceof UsernamePasswordAuthentication) {
UsernamePasswordAuthentication upauth = (UsernamePasswordAuthentication) authentication;
String user = upauth.getUsername();
String password = upauth.getPassword();
if (user == null) {
throw new AuthenticationFailedException("Authentication failed");
}
if (password == null) {
password = "";
}
Statement stmt = null;
ResultSet rs = null;
try {
// create the sql query
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ATTR_LOGIN, escapeString(user));
String sql = StringUtils.replaceString(authenticateStmt, map);
LOG.info(sql);
// execute query
stmt = createConnection().createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
try {
String storedPassword = rs.getString(ATTR_PASSWORD);
if (getPasswordEncryptor().matches(password, storedPassword)) {
return getUserByName(user);
} else {
throw new AuthenticationFailedException(
"Authentication failed");
}
} catch (FtpException e) {
throw new AuthenticationFailedException(
"Authentication failed", e);
}
} else {
throw new AuthenticationFailedException(
"Authentication failed");
}
} catch (SQLException ex) {
LOG.error("DbUserManager.authenticate()", ex);
throw new AuthenticationFailedException(
"Authentication failed", ex);
} finally {
closeQuitely(rs);
closeQuitely(stmt);
}
} else if (authentication instanceof AnonymousAuthentication) {
try {
if (doesExist("anonymous")) {
return getUserByName("anonymous");
} else {
throw new AuthenticationFailedException(
"Authentication failed");
}
} catch (AuthenticationFailedException e) {
throw e;
} catch (FtpException e) {
throw new AuthenticationFailedException(
"Authentication failed", e);
}
} else {
throw new IllegalArgumentException(
"Authentication not supported by this user manager");
}
}
/**
* Escape string to be embedded in SQL statement.
*/
private String escapeString(String input) {
if (input == null) {
return input;
}
StringBuffer valBuf = new StringBuffer(input);
for (int i = 0; i < valBuf.length(); i++) {
char ch = valBuf.charAt(i);
if (ch == '\'' || ch == '\\' || ch == '$' || ch == '^' || ch == '['
|| ch == ']' || ch == '{' || ch == '}') {
valBuf.insert(i, '\\');
i++;
}
}
return valBuf.toString();
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/DbUserManager.java | Java | art | 22,272 |
/*
* 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.usermanager.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
import org.apache.ftpserver.ftplet.User;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Generic user class. The user attributes are:
* <ul>
* <li>userid</li>
* <li>userpassword</li>
* <li>enableflag</li>
* <li>homedirectory</li>
* <li>writepermission</li>
* <li>idletime</li>
* <li>uploadrate</li>
* <li>downloadrate</li>
* </ul>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class BaseUser implements User {
private String name = null;
private String password = null;
private int maxIdleTimeSec = 0; // no limit
private String homeDir = null;
private boolean isEnabled = true;
private List<Authority> authorities = new ArrayList<Authority>();
/**
* Default constructor.
*/
public BaseUser() {
}
/**
* Copy constructor.
*/
public BaseUser(User user) {
name = user.getName();
password = user.getPassword();
authorities = user.getAuthorities();
maxIdleTimeSec = user.getMaxIdleTime();
homeDir = user.getHomeDirectory();
isEnabled = user.getEnabled();
}
/**
* Get the user name.
*/
public String getName() {
return name;
}
/**
* Set user name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the user password.
*/
public String getPassword() {
return password;
}
/**
* Set user password.
*/
public void setPassword(String pass) {
password = pass;
}
public List<Authority> getAuthorities() {
if (authorities != null) {
return Collections.unmodifiableList(authorities);
} else {
return null;
}
}
public void setAuthorities(List<Authority> authorities) {
if (authorities != null) {
this.authorities = Collections.unmodifiableList(authorities);
} else {
this.authorities = null;
}
}
/**
* Get the maximum idle time in second.
*/
public int getMaxIdleTime() {
return maxIdleTimeSec;
}
/**
* Set the maximum idle time in second.
*/
public void setMaxIdleTime(int idleSec) {
maxIdleTimeSec = idleSec;
if (maxIdleTimeSec < 0) {
maxIdleTimeSec = 0;
}
}
/**
* Get the user enable status.
*/
public boolean getEnabled() {
return isEnabled;
}
/**
* Set the user enable status.
*/
public void setEnabled(boolean enb) {
isEnabled = enb;
}
/**
* Get the user home directory.
*/
public String getHomeDirectory() {
return homeDir;
}
/**
* Set the user home directory.
*/
public void setHomeDirectory(String home) {
homeDir = home;
}
/**
* String representation.
*/
public String toString() {
return name;
}
/**
* {@inheritDoc}
*/
public AuthorizationRequest authorize(AuthorizationRequest request) {
// check for no authorities at all
if(authorities == null) {
return null;
}
boolean someoneCouldAuthorize = false;
for (Authority authority : authorities) {
if (authority.canAuthorize(request)) {
someoneCouldAuthorize = true;
request = authority.authorize(request);
// authorization failed, return null
if (request == null) {
return null;
}
}
}
if (someoneCouldAuthorize) {
return request;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
public List<Authority> getAuthorities(Class<? extends Authority> clazz) {
List<Authority> selected = new ArrayList<Authority>();
for (Authority authority : authorities) {
if (authority.getClass().equals(clazz)) {
selected.add(authority);
}
}
return selected;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/BaseUser.java | Java | art | 5,184 |
/*
* 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.usermanager.impl;
import java.net.InetAddress;
import java.security.cert.Certificate;
/**
* <strong>Internal class, do not use directly.</strong>
*
* User metadata used during authentication
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class UserMetadata {
private Certificate[] certificateChain;
private InetAddress inetAddress;
/**
* Retrive the certificate chain used for an SSL connection.
*
* @return The certificate chain, can be null if no peer certificate is
* available (e.g. SSL not used)
*/
public Certificate[] getCertificateChain() {
if (certificateChain != null) {
return certificateChain.clone();
} else {
return null;
}
}
/**
* Set the certificate chain
*
* @param certificateChain
* The certificate chain to set
*/
public void setCertificateChain(final Certificate[] certificateChain) {
if (certificateChain != null) {
this.certificateChain = certificateChain.clone();
} else {
this.certificateChain = null;
}
}
/**
* Retrive the remote IP adress of the client
*
* @return The client IP adress
*/
public InetAddress getInetAddress() {
return inetAddress;
}
/**
* Set the remote IP adress of the client
*
* @param inetAddress
* The client IP adress
*/
public void setInetAddress(final InetAddress inetAddress) {
this.inetAddress = inetAddress;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/UserMetadata.java | Java | art | 2,448 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.Md5PasswordEncryptor;
import org.apache.ftpserver.usermanager.PasswordEncryptor;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Abstract common base type for {@link UserManager} implementations
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public abstract class AbstractUserManager implements UserManager {
public static final String ATTR_LOGIN = "userid";
public static final String ATTR_PASSWORD = "userpassword";
public static final String ATTR_HOME = "homedirectory";
public static final String ATTR_WRITE_PERM = "writepermission";
public static final String ATTR_ENABLE = "enableflag";
public static final String ATTR_MAX_IDLE_TIME = "idletime";
public static final String ATTR_MAX_UPLOAD_RATE = "uploadrate";
public static final String ATTR_MAX_DOWNLOAD_RATE = "downloadrate";
public static final String ATTR_MAX_LOGIN_NUMBER = "maxloginnumber";
public static final String ATTR_MAX_LOGIN_PER_IP = "maxloginperip";
private String adminName;
private PasswordEncryptor passwordEncryptor = new Md5PasswordEncryptor();
/**
* Internal constructor, do not use directly
*/
public AbstractUserManager(String adminName, PasswordEncryptor passwordEncryptor) {
this.adminName = adminName;
this.passwordEncryptor = passwordEncryptor;
}
/**
* Get the admin name.
*/
public String getAdminName() {
return adminName;
}
/**
* @return true if user with this login is administrator
*/
public boolean isAdmin(String login) throws FtpException {
return adminName.equals(login);
}
/**
* Retrieve the password encryptor used for this user manager
* @return The password encryptor. Default to {@link Md5PasswordEncryptor}
* if no other has been provided
*/
public PasswordEncryptor getPasswordEncryptor() {
return passwordEncryptor;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/AbstractUserManager.java | Java | art | 2,980 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Class representing a write request
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class WriteRequest implements AuthorizationRequest {
private String file;
/**
* Request write access to the user home directory (/)
*
*/
public WriteRequest() {
this("/");
}
/**
* Request write access to a file or directory relative to the user home
* directory
*
* @param file
*/
public WriteRequest(final String file) {
this.file = file;
}
/**
* Get the file or directory to which write access is requested
*
* @return the file The file or directory
*/
public String getFile() {
return file;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/WriteRequest.java | Java | art | 1,729 |
/*
* 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.usermanager.impl;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* The max upload rate permission
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TransferRatePermission implements Authority {
private int maxDownloadRate;
private int maxUploadRate;
public TransferRatePermission(int maxDownloadRate, int maxUploadRate) {
this.maxDownloadRate = maxDownloadRate;
this.maxUploadRate = maxUploadRate;
}
/**
* @see Authority#authorize(AuthorizationRequest)
*/
public AuthorizationRequest authorize(AuthorizationRequest request) {
if (request instanceof TransferRateRequest) {
TransferRateRequest transferRateRequest = (TransferRateRequest) request;
transferRateRequest.setMaxDownloadRate(maxDownloadRate);
transferRateRequest.setMaxUploadRate(maxUploadRate);
return transferRateRequest;
} else {
return null;
}
}
/**
* @see Authority#canAuthorize(AuthorizationRequest)
*/
public boolean canAuthorize(AuthorizationRequest request) {
return request instanceof TransferRateRequest;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/impl/TransferRatePermission.java | Java | art | 2,153 |
/*
* 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.usermanager;
import org.apache.ftpserver.ftplet.UserManager;
/**
* Interface for user manager factories
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface UserManagerFactory {
/**
* Create an {@link UserManager} instance based on the configuration on the factory
* @return The {@link UserManager}
*/
UserManager createUserManager();
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/UserManagerFactory.java | Java | art | 1,244 |
/*
* 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.usermanager;
import java.io.File;
import java.net.URL;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.impl.PropertiesUserManager;
/**
* Factory for the properties file based <code>UserManager</code> implementation.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PropertiesUserManagerFactory implements UserManagerFactory {
private String adminName = "admin";
private File userDataFile;
private URL userDataURL;
private PasswordEncryptor passwordEncryptor = new Md5PasswordEncryptor();
/**
* Creates a {@link PropertiesUserManager} instance based on the provided configuration
*/
public UserManager createUserManager() {
if (userDataURL != null) {
return new PropertiesUserManager(passwordEncryptor, userDataURL,
adminName);
} else {
return new PropertiesUserManager(passwordEncryptor, userDataFile,
adminName);
}
}
/**
* Get the admin name.
* @return The admin user name
*/
public String getAdminName() {
return adminName;
}
/**
* Set the name to use as the administrator of the server. The default value
* is "admin".
*
* @param adminName
* The administrator user name
*/
public void setAdminName(String adminName) {
this.adminName = adminName;
}
/**
* Retrieve the file used to load and store users
* @return The file
*/
public File getFile() {
return userDataFile;
}
/**
* Set the file used to store and read users.
*
* @param propFile
* A file containing users
*/
public void setFile(File propFile) {
this.userDataFile = propFile;
}
/**
* Retrieve the URL used to load and store users
* @return The {@link URL}
*/
public URL getUrl() {
return userDataURL;
}
/**
* Set the URL used to store and read users.
*
* @param userDataURL
* A {@link URL} containing users
*/
public void setUrl(URL userDataURL) {
this.userDataURL = userDataURL;
}
/**
* Retrieve the password encryptor used by user managers created by this factory
* @return The password encryptor. Default to {@link Md5PasswordEncryptor}
* if no other has been provided
*/
public PasswordEncryptor getPasswordEncryptor() {
return passwordEncryptor;
}
/**
* Set the password encryptor to use by user managers created by this factory
* @param passwordEncryptor The password encryptor
*/
public void setPasswordEncryptor(PasswordEncryptor passwordEncryptor) {
this.passwordEncryptor = passwordEncryptor;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/PropertiesUserManagerFactory.java | Java | art | 3,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.usermanager;
import java.util.ArrayList;
import java.util.List;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.impl.BaseUser;
/**
* Factory for {@link User} instances.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class UserFactory {
private String name = null;
private String password = null;
private int maxIdleTimeSec = 0; // no limit
private String homeDir = null;
private boolean isEnabled = true;
private List<Authority> authorities = new ArrayList<Authority>();
/**
* Creates a user based on the configuration set on the factory
* @return The created user
*/
public User createUser() {
BaseUser user = new BaseUser();
user.setName(name);
user.setPassword(password);
user.setHomeDirectory(homeDir);
user.setEnabled(isEnabled);
user.setAuthorities(authorities);
user.setMaxIdleTime(maxIdleTimeSec);
return user;
}
/**
* Get the user name for users created by this factory
* @return The user name
*/
public String getName() {
return name;
}
/**
* Set the user name for users created by this factory
* @param name The user name
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the password for users created by this factory
* @return The password
*/
public String getPassword() {
return password;
}
/**
* Set the user name for users created by this factory
* @param password The password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get the max idle time for users created by this factory
* @return The max idle time in seconds
*/
public int getMaxIdleTime() {
return maxIdleTimeSec;
}
/**
* Set the user name for users created by this factory
* @param maxIdleTimeSec The max idle time in seconds
*/
public void setMaxIdleTime(int maxIdleTimeSec) {
this.maxIdleTimeSec = maxIdleTimeSec;
}
/**
* Get the home directory for users created by this factory
* @return The home directory path
*/
public String getHomeDirectory() {
return homeDir;
}
/**
* Set the user name for users created by this factory
* @param homeDir The home directory path
*/
public void setHomeDirectory(String homeDir) {
this.homeDir = homeDir;
}
/**
* Get the enabled status for users created by this factory
* @return true if the user is enabled (allowed to log in)
*/
public boolean isEnabled() {
return isEnabled;
}
/**
* Get the enabled status for users created by this factory
* @param isEnabled true if the user should be enabled (allowed to log in)
*/
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
/**
* Get the authorities for users created by this factory
* @return The authorities
*/
public List<? extends Authority> getAuthorities() {
return authorities;
}
/**
* Set the authorities for users created by this factory
* @param authorities The authorities
*/
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/usermanager/UserFactory.java | Java | art | 4,038 |
/*
* 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.ipfilter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
/**
* An implementation of Mina Filter to filter clients based on the originating
* IP address.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*
*/
public class MinaIpFilter extends IoFilterAdapter {
/**
* The actual <code>IpFilter</code> used by this filter.
*/
private IpFilter filter = null;
/**
* Creates a new instance of <code>MinaIpFilter</code>.
*
* @param filter
* the filter
*/
public MinaIpFilter(IpFilter filter) {
this.filter = filter;
}
@Override
public void sessionCreated(NextFilter nextFilter, IoSession session) {
SocketAddress remoteAddress = session.getRemoteAddress();
if (remoteAddress instanceof InetSocketAddress) {
InetAddress ipAddress = ((InetSocketAddress) remoteAddress).getAddress();
// TODO we probably have to check if the InetAddress is a version 4
// address, or else, the result would probably be unknown.
if (!filter.accept(ipAddress)) {
session.close(true);
}
else {
nextFilter.sessionCreated(session);
}
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ipfilter/MinaIpFilter.java | Java | art | 2,171 |
/*
* 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.ipfilter;
/**
* Defines various types of IP Filters.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*
*/
public enum IpFilterType {
/**
* filter type that allows a set of predefined IP addresses, also known as a
* white list.
*/
ALLOW,
/**
* filter type that blocks a set of predefined IP addresses, also known as a
* black list.
*/
DENY;
/**
* Parses the given string into its equivalent enum.
*
* @param value
* the string value to parse.
* @return the equivalent enum
*/
public static IpFilterType parse(String value) {
for (IpFilterType type : values()) {
if (type.name().equalsIgnoreCase(value)) {
return type;
}
}
throw new IllegalArgumentException("Invalid IpFilterType: " + value);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ipfilter/IpFilterType.java | Java | art | 1,682 |
/*
* 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.ipfilter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.mina.filter.firewall.Subnet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of the <code>IpFilter</code> interface, which uses
* specific IP addresses or ranges of IP addresses that can be blocked or
* allowed.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*
*/
public class DefaultIpFilter extends CopyOnWriteArraySet<Subnet> implements
IpFilter {
/**
* Logger
*/
Logger LOGGER = LoggerFactory.getLogger(DefaultIpFilter.class);
/**
* Serial version UID
*/
private static final long serialVersionUID = 4887092372700628783L;
/**
* filter type
*/
private IpFilterType type = null;
/**
* Creates a new instance of <code>DefaultIpFilter</code>.
*
* @param type
* the filter type
*/
public DefaultIpFilter(IpFilterType type) {
this(type, new HashSet<Subnet>(0));
}
/**
* Creates a new instance of <code>DefaultIpFilter</code>.
*
* @param type
* the filter type
* @param collection
* a collection of <code>Subnet</code>s to filter out/in.
*/
public DefaultIpFilter(IpFilterType type,
Collection<? extends Subnet> collection) {
super(collection);
this.type = type;
}
/**
* Creates a new instance of <code>DefaultIpFilter</code>.
*
* @param type
* the filter type
* @param addresses
* a comma, space, tab, LF separated list of IP addresses/CIDRs.
* @throws UnknownHostException
* propagated
* @throws NumberFormatException
* propagated
*/
public DefaultIpFilter(IpFilterType type, String addresses)
throws NumberFormatException, UnknownHostException {
super();
this.type = type;
if (addresses != null) {
String[] tokens = addresses.split("[\\s,]+");
for (String token : tokens) {
if (token.trim().length() > 0) {
add(token);
}
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Created DefaultIpFilter of type {} with the subnets {}", type,
this);
}
}
/**
* Returns the type of this filter.
*
* @return the type of this filter.
*/
public IpFilterType getType() {
return type;
}
/**
* Sets the type of this filter.
*
* @param type
* the type of this filter.
*/
// TODO should we allow changing the filter type once it is created? I don't
// think we should.
public void setType(IpFilterType type) {
this.type = type;
}
/**
* Adds the given string representation of InetAddress or CIDR notation to
* this filter.
*
* @param str
* the string representation of InetAddress or CIDR notation
* @return if the given element was added or not. <code>true</code>, if the
* given element was added to the filter; <code>false</code>, if the
* element already exists in the filter.
* @throws NumberFormatException
* propagated
* @throws UnknownHostException
* propagated
*/
public boolean add(String str) throws NumberFormatException,
UnknownHostException {
// This is required so we do not block loopback address if some one adds
// a string with blanks as the InetAddress class assumes loopback
// address on blank string.
if (str.trim().length() < 1) {
throw new IllegalArgumentException("Invalid IP Address or Subnet: "
+ str);
}
String[] tokens = str.split("/");
if (tokens.length == 2) {
return add(new Subnet(InetAddress.getByName(tokens[0]),
Integer.parseInt(tokens[1])));
}
else {
return add(new Subnet(InetAddress.getByName(tokens[0]), 32));
}
}
public boolean accept(InetAddress address) {
switch (type) {
case ALLOW:
for (Subnet subnet : this) {
if (subnet.inSubnet(address)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Allowing connection from {} because it matches with the whitelist subnet {}",
new Object[] { address, subnet });
}
return true;
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Denying connection from {} because it does not match any of the whitelist subnets",
new Object[] { address });
}
return false;
case DENY:
if (isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Allowing connection from {} because blacklist is empty",
new Object[] { address });
}
return true;
}
for (Subnet subnet : this) {
if (subnet.inSubnet(address)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Denying connection from {} because it matches with the blacklist subnet {}",
new Object[] { address, subnet });
}
return false;
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Allowing connection from {} because it does not match any of the blacklist subnets",
new Object[] { address });
}
return true;
default:
throw new RuntimeException(
"Unknown or unimplemented filter type: " + type);
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ipfilter/DefaultIpFilter.java | Java | art | 6,254 |
/*
* 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.ipfilter;
import java.net.InetAddress;
/**
* The interface for filtering connections based on the client's IP address.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*
*/
public interface IpFilter {
/**
* Tells whether or not the given IP address is accepted by this filter.
*
* @param address
* the IP address to check
* @return <code>true</code>, if the given IP address is accepted by this
* filter; <code>false</code>, otherwise.
*/
public boolean accept(InetAddress address);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/ipfilter/IpFilter.java | Java | art | 1,433 |
<!--
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>
</body>
</html>
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/package.html | HTML | art | 941 |
/*
* 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.impl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.ftpserver.DataConnectionException;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public interface ServerDataConnectionFactory extends DataConnectionFactory {
/**
* Port command.
*/
void initActiveDataConnection(InetSocketAddress address);
/**
* Initiate the passive data connection.
*
* @return The {@link InetSocketAddress} on which the data connection if
* bound.
*/
InetSocketAddress initPassiveDataConnection()
throws DataConnectionException;
/**
* Set the security protocol.
*/
void setSecure(boolean secure);
/**
* Sets the server's control address.
*/
void setServerControlAddress(InetAddress serverControlAddress);
void setZipMode(boolean zip);
/**
* Check the data connection idle status.
*/
boolean isTimeout(long currTime);
/**
* Dispose data connection - close all the sockets.
*/
void dispose();
/**
* Is secure?
*/
boolean isSecure();
/**
* Is zip mode?
*/
boolean isZipMode();
/**
* Get client address.
*/
InetAddress getInetAddress();
/**
* Get port number.
*/
int getPort();
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/ServerDataConnectionFactory.java | Java | art | 2,302 |
/*
* 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.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.message.MessageResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is the starting point of all the servers. It invokes a new listener
* thread. <code>Server</code> implementation is used to create the server
* socket and handle client connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpServer implements FtpServer {
private final Logger LOG = LoggerFactory.getLogger(DefaultFtpServer.class);
private FtpServerContext serverContext;
private boolean suspended = false;
private boolean started = false;
/**
* Internal constructor, do not use directly. Use {@link FtpServerFactory} instead
*/
public DefaultFtpServer(final FtpServerContext serverContext) {
this.serverContext = serverContext;
}
/**
* Start the server. Open a new listener thread.
* @throws FtpException
*/
public void start() throws FtpException {
if (serverContext == null) {
// we have already been stopped, can not be restarted
throw new IllegalStateException("FtpServer has been stopped. Restart is not supported");
}
List<Listener> startedListeners = new ArrayList<Listener>();
try {
Map<String, Listener> listeners = serverContext.getListeners();
for (Listener listener : listeners.values()) {
listener.start(serverContext);
startedListeners.add(listener);
}
// init the Ftplet container
serverContext.getFtpletContainer().init(serverContext);
started = true;
LOG.info("FTP server started");
} catch(Exception e) {
// must close listeners that we were able to start
for(Listener listener : startedListeners) {
listener.stop();
}
if(e instanceof FtpException) {
throw (FtpException)e;
} else {
throw (RuntimeException)e;
}
}
}
/**
* Stop the server. Stopping the server will close completely and
* it not supported to restart using {@link #start()}.
*/
public void stop() {
if (serverContext == null) {
// we have already been stopped, ignore
return;
}
// stop all listeners
Map<String, Listener> listeners = serverContext.getListeners();
for (Listener listener : listeners.values()) {
listener.stop();
}
// destroy the Ftplet container
serverContext.getFtpletContainer().destroy();
// release server resources
if (serverContext != null) {
serverContext.dispose();
serverContext = null;
}
started = false;
}
/**
* Get the server status.
*/
public boolean isStopped() {
return !started;
}
/**
* Suspend further requests
*/
public void suspend() {
if (!started) {
return;
}
LOG.debug("Suspending server");
// stop all listeners
Map<String, Listener> listeners = serverContext.getListeners();
for (Listener listener : listeners.values()) {
listener.suspend();
}
suspended = true;
LOG.debug("Server suspended");
}
/**
* Resume the server handler
*/
public void resume() {
if (!suspended) {
return;
}
LOG.debug("Resuming server");
Map<String, Listener> listeners = serverContext.getListeners();
for (Listener listener : listeners.values()) {
listener.resume();
}
suspended = false;
LOG.debug("Server resumed");
}
/**
* Is the server suspended
*/
public boolean isSuspended() {
return suspended;
}
/**
* Get the root server context.
*/
public FtpServerContext getServerContext() {
return serverContext;
}
/**
* Get all listeners available one this server
*
* @return The current listeners
*/
public Map<String, Listener> getListeners() {
return getServerContext().getListeners();
}
/**
* Get a specific listener identified by its name
*
* @param name
* The name of the listener
* @return The {@link Listener} matching the provided name
*/
public Listener getListener(final String name) {
return getServerContext().getListener(name);
}
/**
* Get all {@link Ftplet}s registered at this server
*
* @return All {@link Ftplet}s
*/
public Map<String, Ftplet> getFtplets() {
return getServerContext().getFtpletContainer().getFtplets();
}
/**
* Retrieve the user manager used with this server
*
* @return The user manager
*/
public UserManager getUserManager() {
return getServerContext().getUserManager();
}
/**
* Retrieve the file system used with this server
*
* @return The {@link FileSystemFactory}
*/
public FileSystemFactory getFileSystem() {
return getServerContext().getFileSystemManager();
}
/**
* Retrieve the command factory used with this server
*
* @return The {@link CommandFactory}
*/
public CommandFactory getCommandFactory() {
return getServerContext().getCommandFactory();
}
/**
* Retrieve the message resource used with this server
*
* @return The {@link MessageResource}
*/
public MessageResource getMessageResource() {
return getServerContext().getMessageResource();
}
/**
* Retrieve the connection configuration this server
*
* @return The {@link MessageResource}
*/
public ConnectionConfig getConnectionConfig() {
return getServerContext().getConnectionConfig();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpServer.java | Java | art | 7,478 |
/*
* 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.impl;
import java.net.InetSocketAddress;
import java.security.cert.Certificate;
import java.util.Date;
import java.util.UUID;
import org.apache.ftpserver.ftplet.DataConnectionFactory;
import org.apache.ftpserver.ftplet.DataType;
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.FtpSession;
import org.apache.ftpserver.ftplet.Structure;
import org.apache.ftpserver.ftplet.User;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FTP session
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpSession implements FtpSession {
private FtpIoSession ioSession;
/**
* Default constructor.
*/
public DefaultFtpSession(final FtpIoSession ioSession) {
this.ioSession = ioSession;
}
/**
* Is logged-in
*/
public boolean isLoggedIn() {
return ioSession.isLoggedIn();
}
/**
* Get FTP data connection.
*/
public DataConnectionFactory getDataConnection() {
return ioSession.getDataConnection();
}
/**
* Get file system view.
*/
public FileSystemView getFileSystemView() {
return ioSession.getFileSystemView();
}
/**
* Get connection time.
*/
public Date getConnectionTime() {
return new Date(ioSession.getCreationTime());
}
/**
* Get the login time.
*/
public Date getLoginTime() {
return ioSession.getLoginTime();
}
/**
* Get last access time.
*/
public Date getLastAccessTime() {
return ioSession.getLastAccessTime();
}
/**
* Get file offset.
*/
public long getFileOffset() {
return ioSession.getFileOffset();
}
/**
* Get rename from file object.
*/
public FtpFile getRenameFrom() {
return ioSession.getRenameFrom();
}
/**
* Returns user name entered in USER command
*
* @return user name entered in USER command
*/
public String getUserArgument() {
return ioSession.getUserArgument();
}
/**
* Get language.
*/
public String getLanguage() {
return ioSession.getLanguage();
}
/**
* Get user.
*/
public User getUser() {
return ioSession.getUser();
}
/**
* Get remote address
*/
public InetSocketAddress getClientAddress() {
if (ioSession.getRemoteAddress() instanceof InetSocketAddress) {
return ((InetSocketAddress) ioSession.getRemoteAddress());
} else {
return null;
}
}
/**
* Get attribute
*/
public Object getAttribute(final String name) {
if (name.startsWith(FtpIoSession.ATTRIBUTE_PREFIX)) {
throw new IllegalArgumentException(
"Illegal lookup of internal attribute");
}
return ioSession.getAttribute(name);
}
/**
* Set attribute.
*/
public void setAttribute(final String name, final Object value) {
if (name.startsWith(FtpIoSession.ATTRIBUTE_PREFIX)) {
throw new IllegalArgumentException(
"Illegal setting of internal attribute");
}
ioSession.setAttribute(name, value);
}
public int getMaxIdleTime() {
return ioSession.getMaxIdleTime();
}
public void setMaxIdleTime(final int maxIdleTime) {
ioSession.setMaxIdleTime(maxIdleTime);
}
/**
* Get the data type.
*/
public DataType getDataType() {
return ioSession.getDataType();
}
/**
* Get structure.
*/
public Structure getStructure() {
return ioSession.getStructure();
}
public Certificate[] getClientCertificates() {
return ioSession.getClientCertificates();
}
public InetSocketAddress getServerAddress() {
if (ioSession.getLocalAddress() instanceof InetSocketAddress) {
return ((InetSocketAddress) ioSession.getLocalAddress());
} else {
return null;
}
}
public int getFailedLogins() {
return ioSession.getFailedLogins();
}
public void removeAttribute(final String name) {
if (name.startsWith(FtpIoSession.ATTRIBUTE_PREFIX)) {
throw new IllegalArgumentException(
"Illegal removal of internal attribute");
}
ioSession.removeAttribute(name);
}
public void write(FtpReply reply) throws FtpException {
ioSession.write(reply);
}
public boolean isSecure() {
// TODO Auto-generated method stub
return ioSession.isSecure();
}
/**
* Increase the number of bytes written on the data connection
* @param increment The number of bytes written
*/
public void increaseWrittenDataBytes(int increment) {
ioSession.increaseWrittenDataBytes(increment);
}
/**
* Increase the number of bytes read on the data connection
* @param increment The number of bytes written
*/
public void increaseReadDataBytes(int increment) {
ioSession.increaseReadDataBytes(increment);
}
/**
* {@inheritDoc}
*/
public UUID getSessionId() {
return ioSession.getSessionId();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpSession.java | Java | art | 6,280 |
/*
* 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.impl;
import java.io.IOException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.listener.Listener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public interface FtpHandler {
void init(FtpServerContext context, Listener listener);
/**
* Invoked from an I/O processor thread when a new connection has been
* created. Because this method is supposed to be called from the same
* thread that handles I/O of multiple sessions, please implement this
* method to perform tasks that consumes minimal amount of time such as
* socket parameter and user-defined session attribute initialization.
*/
void sessionCreated(FtpIoSession session) throws Exception;
/**
* Invoked when a connection has been opened. This method is invoked after
* {@link #sessionCreated(IoSession)}. The biggest difference from
* {@link #sessionCreated(IoSession)} is that it's invoked from other thread
* than an I/O processor thread once thread modesl is configured properly.
*/
void sessionOpened(FtpIoSession session) throws Exception;
/**
* Invoked when a connection is closed.
*/
void sessionClosed(FtpIoSession session) throws Exception;
/**
* Invoked with the related {@link IdleStatus} when a connection becomes
* idle. This method is not invoked if the transport type is UDP; it's a
* known bug, and will be fixed in 2.0.
*/
void sessionIdle(FtpIoSession session, IdleStatus status) throws Exception;
/**
* Invoked when any exception is thrown by user {@link IoHandler}
* implementation or by MINA. If <code>cause</code> is instanceof
* {@link IOException}, MINA will close the connection automatically.
*/
void exceptionCaught(FtpIoSession session, Throwable cause)
throws Exception;
/**
* Invoked when a message is received.
*/
void messageReceived(FtpIoSession session, FtpRequest request)
throws Exception;
/**
* Invoked when a message written by {@link IoSession#write(Object)} is sent
* out.
*/
void messageSent(FtpIoSession session, FtpReply reply) throws Exception;
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/FtpHandler.java | Java | art | 3,321 |
/*
* 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.impl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpStatistics;
import org.apache.ftpserver.message.MessageResource;
import org.apache.ftpserver.util.DateUtils;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FTP reply translator.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class LocalizedFtpReply extends DefaultFtpReply {
public static final String CLIENT_ACCESS_TIME = "client.access.time";
public static final String CLIENT_CON_TIME = "client.con.time";
public static final String CLIENT_DIR = "client.dir";
public static final String CLIENT_HOME = "client.home";
public static final String CLIENT_IP = "client.ip";
public static final String CLIENT_LOGIN_NAME = "client.login.name";
public static final String CLIENT_LOGIN_TIME = "client.login.time";
public static final String OUTPUT_CODE = "output.code";
public static final String OUTPUT_MSG = "output.msg";
public static final String REQUEST_ARG = "request.arg";
public static final String REQUEST_CMD = "request.cmd";
public static final String REQUEST_LINE = "request.line";
// /////////////////////// All Server Vatiables /////////////////////////
public static final String SERVER_IP = "server.ip";
public static final String SERVER_PORT = "server.port";
public static final String STAT_CON_CURR = "stat.con.curr";
public static final String STAT_CON_TOTAL = "stat.con.total";
public static final String STAT_DIR_CREATE_COUNT = "stat.dir.create.count";
public static final String STAT_DIR_DELETE_COUNT = "stat.dir.delete.count";
public static final String STAT_FILE_DELETE_COUNT = "stat.file.delete.count";
public static final String STAT_FILE_DOWNLOAD_BYTES = "stat.file.download.bytes";
public static final String STAT_FILE_DOWNLOAD_COUNT = "stat.file.download.count";
public static final String STAT_FILE_UPLOAD_BYTES = "stat.file.upload.bytes";
public static final String STAT_FILE_UPLOAD_COUNT = "stat.file.upload.count";
public static final String STAT_LOGIN_ANON_CURR = "stat.login.anon.curr";
public static final String STAT_LOGIN_ANON_TOTAL = "stat.login.anon.total";
public static final String STAT_LOGIN_CURR = "stat.login.curr";
public static final String STAT_LOGIN_TOTAL = "stat.login.total";
public static final String STAT_START_TIME = "stat.start.time";
public static LocalizedFtpReply translate(FtpIoSession session, FtpRequest request,
FtpServerContext context, int code, String subId, String basicMsg) {
String msg = translateMessage(session, request, context, code, subId,
basicMsg);
return new LocalizedFtpReply(code, msg);
}
private static String translateMessage(FtpIoSession session,
FtpRequest request, FtpServerContext context, int code,
String subId, String basicMsg) {
MessageResource resource = context.getMessageResource();
String lang = session.getLanguage();
String msg = null;
if (resource != null) {
msg = resource.getMessage(code, subId, lang);
}
if (msg == null) {
msg = "";
}
msg = replaceVariables(session, request, context, code, basicMsg, msg);
return msg;
}
/**
* Replace server variables.
*/
private static String replaceVariables(FtpIoSession session,
FtpRequest request, FtpServerContext context, int code,
String basicMsg, String str) {
int startIndex = 0;
int openIndex = str.indexOf('{', startIndex);
if (openIndex == -1) {
return str;
}
int closeIndex = str.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
return str;
}
StringBuffer sb = new StringBuffer(128);
sb.append(str.substring(startIndex, openIndex));
while (true) {
String varName = str.substring(openIndex + 1, closeIndex);
sb.append(getVariableValue(session, request, context, code,
basicMsg, varName));
startIndex = closeIndex + 1;
openIndex = str.indexOf('{', startIndex);
if (openIndex == -1) {
sb.append(str.substring(startIndex));
break;
}
closeIndex = str.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
sb.append(str.substring(startIndex));
break;
}
sb.append(str.substring(startIndex, openIndex));
}
return sb.toString();
}
/**
* Get the variable value.
*/
private static String getVariableValue(FtpIoSession session,
FtpRequest request, FtpServerContext context, int code,
String basicMsg, String varName) {
String varVal = null;
// all output variables
if (varName.startsWith("output.")) {
varVal = getOutputVariableValue(session, code, basicMsg, varName);
}
// all server variables
else if (varName.startsWith("server.")) {
varVal = getServerVariableValue(session, varName);
}
// all request variables
else if (varName.startsWith("request.")) {
varVal = getRequestVariableValue(session, request, varName);
}
// all statistical variables
else if (varName.startsWith("stat.")) {
varVal = getStatisticalVariableValue(session, context, varName);
}
// all client variables
else if (varName.startsWith("client.")) {
varVal = getClientVariableValue(session, varName);
}
if (varVal == null) {
varVal = "";
}
return varVal;
}
/**
* Get client variable value.
*/
private static String getClientVariableValue(FtpIoSession session,
String varName) {
String varVal = null;
// client ip
if (varName.equals(CLIENT_IP)) {
if (session.getRemoteAddress() instanceof InetSocketAddress) {
InetSocketAddress remoteSocketAddress = (InetSocketAddress) session
.getRemoteAddress();
varVal = remoteSocketAddress.getAddress().getHostAddress();
}
}
// client connection time
else if (varName.equals(CLIENT_CON_TIME)) {
varVal = DateUtils.getISO8601Date(session.getCreationTime());
}
// client login name
else if (varName.equals(CLIENT_LOGIN_NAME)) {
if (session.getUser() != null) {
varVal = session.getUser().getName();
}
}
// client login time
else if (varName.equals(CLIENT_LOGIN_TIME)) {
varVal = DateUtils.getISO8601Date(session.getLoginTime().getTime());
}
// client last access time
else if (varName.equals(CLIENT_ACCESS_TIME)) {
varVal = DateUtils.getISO8601Date(session.getLastAccessTime()
.getTime());
}
// client home
else if (varName.equals(CLIENT_HOME)) {
varVal = session.getUser().getHomeDirectory();
}
// client directory
else if (varName.equals(CLIENT_DIR)) {
FileSystemView fsView = session.getFileSystemView();
if (fsView != null) {
try {
varVal = fsView.getWorkingDirectory().getAbsolutePath();
} catch (Exception ex) {
varVal = "";
}
}
}
return varVal;
}
/**
* Get output variable value.
*/
private static String getOutputVariableValue(FtpIoSession session,
int code, String basicMsg, String varName) {
String varVal = null;
// output code
if (varName.equals(OUTPUT_CODE)) {
varVal = String.valueOf(code);
}
// output message
else if (varName.equals(OUTPUT_MSG)) {
varVal = basicMsg;
}
return varVal;
}
/**
* Get request variable value.
*/
private static String getRequestVariableValue(FtpIoSession session,
FtpRequest request, String varName) {
String varVal = null;
if (request == null) {
return "";
}
// request line
if (varName.equals(REQUEST_LINE)) {
varVal = request.getRequestLine();
}
// request command
else if (varName.equals(REQUEST_CMD)) {
varVal = request.getCommand();
}
// request argument
else if (varName.equals(REQUEST_ARG)) {
varVal = request.getArgument();
}
return varVal;
}
/**
* Get server variable value.
*/
private static String getServerVariableValue(FtpIoSession session,
String varName) {
String varVal = null;
SocketAddress localSocketAddress = session.getLocalAddress();
if (localSocketAddress instanceof InetSocketAddress) {
InetSocketAddress localInetSocketAddress = (InetSocketAddress) localSocketAddress;
// server address
if (varName.equals(SERVER_IP)) {
InetAddress addr = localInetSocketAddress.getAddress();
if (addr != null) {
varVal = addr.getHostAddress();
}
}
// server port
else if (varName.equals(SERVER_PORT)) {
varVal = String.valueOf(localInetSocketAddress.getPort());
}
}
return varVal;
}
/**
* Get statistical connection variable value.
*/
private static String getStatisticalConnectionVariableValue(
FtpIoSession session, FtpServerContext context, String varName) {
String varVal = null;
FtpStatistics stat = context.getFtpStatistics();
// total connection number
if (varName.equals(STAT_CON_TOTAL)) {
varVal = String.valueOf(stat.getTotalConnectionNumber());
}
// current connection number
else if (varName.equals(STAT_CON_CURR)) {
varVal = String.valueOf(stat.getCurrentConnectionNumber());
}
return varVal;
}
/**
* Get statistical directory variable value.
*/
private static String getStatisticalDirectoryVariableValue(
FtpIoSession session, FtpServerContext context, String varName) {
String varVal = null;
FtpStatistics stat = context.getFtpStatistics();
// total directory created
if (varName.equals(STAT_DIR_CREATE_COUNT)) {
varVal = String.valueOf(stat.getTotalDirectoryCreated());
}
// total directory removed
else if (varName.equals(STAT_DIR_DELETE_COUNT)) {
varVal = String.valueOf(stat.getTotalDirectoryRemoved());
}
return varVal;
}
/**
* Get statistical file variable value.
*/
private static String getStatisticalFileVariableValue(FtpIoSession session,
FtpServerContext context, String varName) {
String varVal = null;
FtpStatistics stat = context.getFtpStatistics();
// total number of file upload
if (varName.equals(STAT_FILE_UPLOAD_COUNT)) {
varVal = String.valueOf(stat.getTotalUploadNumber());
}
// total bytes uploaded
else if (varName.equals(STAT_FILE_UPLOAD_BYTES)) {
varVal = String.valueOf(stat.getTotalUploadSize());
}
// total number of file download
else if (varName.equals(STAT_FILE_DOWNLOAD_COUNT)) {
varVal = String.valueOf(stat.getTotalDownloadNumber());
}
// total bytes downloaded
else if (varName.equals(STAT_FILE_DOWNLOAD_BYTES)) {
varVal = String.valueOf(stat.getTotalDownloadSize());
}
// total number of files deleted
else if (varName.equals(STAT_FILE_DELETE_COUNT)) {
varVal = String.valueOf(stat.getTotalDeleteNumber());
}
return varVal;
}
/**
* Get statistical login variable value.
*/
private static String getStatisticalLoginVariableValue(
FtpIoSession session, FtpServerContext context, String varName) {
String varVal = null;
FtpStatistics stat = context.getFtpStatistics();
// total login number
if (varName.equals(STAT_LOGIN_TOTAL)) {
varVal = String.valueOf(stat.getTotalLoginNumber());
}
// current login number
else if (varName.equals(STAT_LOGIN_CURR)) {
varVal = String.valueOf(stat.getCurrentLoginNumber());
}
// total anonymous login number
else if (varName.equals(STAT_LOGIN_ANON_TOTAL)) {
varVal = String.valueOf(stat.getTotalAnonymousLoginNumber());
}
// current anonymous login number
else if (varName.equals(STAT_LOGIN_ANON_CURR)) {
varVal = String.valueOf(stat.getCurrentAnonymousLoginNumber());
}
return varVal;
}
/**
* Get statistical variable value.
*/
private static String getStatisticalVariableValue(FtpIoSession session,
FtpServerContext context, String varName) {
String varVal = null;
FtpStatistics stat = context.getFtpStatistics();
// server start time
if (varName.equals(STAT_START_TIME)) {
varVal = DateUtils.getISO8601Date(stat.getStartTime().getTime());
}
// connection statistical variables
else if (varName.startsWith("stat.con")) {
varVal = getStatisticalConnectionVariableValue(session, context,
varName);
}
// login statistical variables
else if (varName.startsWith("stat.login.")) {
varVal = getStatisticalLoginVariableValue(session, context, varName);
}
// file statistical variable
else if (varName.startsWith("stat.file")) {
varVal = getStatisticalFileVariableValue(session, context, varName);
}
// directory statistical variable
else if (varName.startsWith("stat.dir.")) {
varVal = getStatisticalDirectoryVariableValue(session, context,
varName);
}
return varVal;
}
/**
* Private constructor, only allow creating through factory method
*/
private LocalizedFtpReply(int code, String message) {
super(code, message);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/LocalizedFtpReply.java | Java | art | 15,869 |
/*
* 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.impl;
import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.ConnectionConfigFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class DefaultConnectionConfig implements ConnectionConfig {
private int maxLogins = 10;
private boolean anonymousLoginEnabled = true;
private int maxAnonymousLogins = 10;
private int maxLoginFailures = 3;
private int loginFailureDelay = 500;
private int maxThreads = 0;
/**
* Internal constructor, do not use directly. Use {@link ConnectionConfigFactory} instead
*/
public DefaultConnectionConfig(boolean anonymousLoginEnabled,
int loginFailureDelay, int maxLogins, int maxAnonymousLogins,
int maxLoginFailures, int maxThreads) {
this.anonymousLoginEnabled = anonymousLoginEnabled;
this.loginFailureDelay = loginFailureDelay;
this.maxLogins = maxLogins;
this.maxAnonymousLogins = maxAnonymousLogins;
this.maxLoginFailures = maxLoginFailures;
this.maxThreads = maxThreads;
}
public int getLoginFailureDelay() {
return loginFailureDelay;
}
public int getMaxAnonymousLogins() {
return maxAnonymousLogins;
}
public int getMaxLoginFailures() {
return maxLoginFailures;
}
public int getMaxLogins() {
return maxLogins;
}
public boolean isAnonymousLoginEnabled() {
return anonymousLoginEnabled;
}
public int getMaxThreads() {
return maxThreads;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultConnectionConfig.java | Java | art | 2,470 |
/*
* 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.impl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionException;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ssl.ClientAuth;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* We can get the FTP data connection using this class. It uses either PORT or
* PASV command.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IODataConnectionFactory implements ServerDataConnectionFactory {
private final Logger LOG = LoggerFactory
.getLogger(IODataConnectionFactory.class);
private FtpServerContext serverContext;
private Socket dataSoc;
ServerSocket servSoc;
InetAddress address;
int port = 0;
long requestTime = 0L;
boolean passive = false;
boolean secure = false;
private boolean isZip = false;
InetAddress serverControlAddress;
FtpIoSession session;
public IODataConnectionFactory(final FtpServerContext serverContext,
final FtpIoSession session) {
this.session = session;
this.serverContext = serverContext;
if (session.getListener().getDataConnectionConfiguration()
.isImplicitSsl()) {
secure = true;
}
}
/**
* Close data socket.
* This method must be idempotent as we might call it multiple times during disconnect.
*/
public synchronized void closeDataConnection() {
// close client socket if any
if (dataSoc != null) {
try {
dataSoc.close();
} catch (Exception ex) {
LOG.warn("FtpDataConnection.closeDataSocket()", ex);
}
dataSoc = null;
}
// close server socket if any
if (servSoc != null) {
try {
servSoc.close();
} catch (Exception ex) {
LOG.warn("FtpDataConnection.closeDataSocket()", ex);
}
if (session != null) {
DataConnectionConfiguration dcc = session.getListener()
.getDataConnectionConfiguration();
if (dcc != null) {
dcc.releasePassivePort(port);
}
}
servSoc = null;
}
// reset request time
requestTime = 0L;
}
/**
* Port command.
*/
public synchronized void initActiveDataConnection(
final InetSocketAddress address) {
// close old sockets if any
closeDataConnection();
// set variables
passive = false;
this.address = address.getAddress();
port = address.getPort();
requestTime = System.currentTimeMillis();
}
private SslConfiguration getSslConfiguration() {
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;
}
/**
* Initiate a data connection in passive mode (server listening).
*/
public synchronized InetSocketAddress initPassiveDataConnection()
throws DataConnectionException {
LOG.debug("Initiating passive data connection");
// close old sockets if any
closeDataConnection();
// get the passive port
int passivePort = session.getListener()
.getDataConnectionConfiguration().requestPassivePort();
if (passivePort == -1) {
servSoc = null;
throw new DataConnectionException(
"Cannot find an available passive port.");
}
// open passive server socket and get parameters
try {
DataConnectionConfiguration dataCfg = session.getListener()
.getDataConnectionConfiguration();
String passiveAddress = dataCfg.getPassiveAddress();
if (passiveAddress == null) {
address = serverControlAddress;
} else {
address = resolveAddress(dataCfg.getPassiveAddress());
}
if (secure) {
LOG
.debug(
"Opening SSL passive data connection on address \"{}\" and port {}",
address, passivePort);
SslConfiguration ssl = getSslConfiguration();
if (ssl == null) {
throw new DataConnectionException(
"Data connection SSL required but not configured.");
}
// this method does not actually create the SSL socket, due to a JVM bug
// (https://issues.apache.org/jira/browse/FTPSERVER-241).
// Instead, it creates a regular
// ServerSocket that will be wrapped as a SSL socket in createDataSocket()
servSoc = new ServerSocket(passivePort, 0, address);
LOG
.debug(
"SSL Passive data connection created on address \"{}\" and port {}",
address, passivePort);
} else {
LOG
.debug(
"Opening passive data connection on address \"{}\" and port {}",
address, passivePort);
servSoc = new ServerSocket(passivePort, 0, address);
LOG
.debug(
"Passive data connection created on address \"{}\" and port {}",
address, passivePort);
}
port = servSoc.getLocalPort();
servSoc.setSoTimeout(dataCfg.getIdleTime() * 1000);
// set different state variables
passive = true;
requestTime = System.currentTimeMillis();
return new InetSocketAddress(address, port);
} catch (Exception ex) {
servSoc = null;
closeDataConnection();
throw new DataConnectionException(
"Failed to initate passive data connection: "
+ ex.getMessage(), ex);
}
}
/*
* (non-Javadoc)
*
* @see org.apache.ftpserver.FtpDataConnectionFactory2#getInetAddress()
*/
public InetAddress getInetAddress() {
return address;
}
/*
* (non-Javadoc)
*
* @see org.apache.ftpserver.FtpDataConnectionFactory2#getPort()
*/
public int getPort() {
return port;
}
/*
* (non-Javadoc)
*
* @see org.apache.ftpserver.FtpDataConnectionFactory2#openConnection()
*/
public DataConnection openConnection() throws Exception {
return new IODataConnection(createDataSocket(), session, this);
}
/**
* Get the data socket. In case of error returns null.
*/
private synchronized Socket createDataSocket() throws Exception {
// get socket depending on the selection
dataSoc = null;
DataConnectionConfiguration dataConfig = session.getListener()
.getDataConnectionConfiguration();
try {
if (!passive) {
if (secure) {
LOG.debug("Opening secure active data connection");
SslConfiguration ssl = getSslConfiguration();
if (ssl == null) {
throw new FtpException(
"Data connection SSL not configured");
}
// get socket factory
SSLContext ctx = ssl.getSSLContext();
SSLSocketFactory socFactory = ctx.getSocketFactory();
// create socket
SSLSocket ssoc = (SSLSocket) socFactory.createSocket();
ssoc.setUseClientMode(false);
// initialize socket
if (ssl.getEnabledCipherSuites() != null) {
ssoc.setEnabledCipherSuites(ssl.getEnabledCipherSuites());
}
dataSoc = ssoc;
} else {
LOG.debug("Opening active data connection");
dataSoc = new Socket();
}
dataSoc.setReuseAddress(true);
InetAddress localAddr = resolveAddress(dataConfig
.getActiveLocalAddress());
// if no local address has been configured, make sure we use the same as the client connects from
if(localAddr == null) {
localAddr = ((InetSocketAddress)session.getLocalAddress()).getAddress();
}
SocketAddress localSocketAddress = new InetSocketAddress(localAddr, dataConfig.getActiveLocalPort());
LOG.debug("Binding active data connection to {}", localSocketAddress);
dataSoc.bind(localSocketAddress);
dataSoc.connect(new InetSocketAddress(address, port));
} else {
if (secure) {
LOG.debug("Opening secure passive data connection");
// this is where we wrap the unsecured socket as a SSLSocket. This is
// due to the JVM bug described in FTPSERVER-241.
// get server socket factory
SslConfiguration ssl = getSslConfiguration();
// we've already checked this, but let's do it again
if (ssl == null) {
throw new FtpException(
"Data connection SSL not configured");
}
SSLContext ctx = ssl.getSSLContext();
SSLSocketFactory ssocketFactory = ctx.getSocketFactory();
Socket serverSocket = servSoc.accept();
SSLSocket sslSocket = (SSLSocket) ssocketFactory
.createSocket(serverSocket, serverSocket
.getInetAddress().getHostName(),
serverSocket.getPort(), true);
sslSocket.setUseClientMode(false);
// initialize server socket
if (ssl.getClientAuth() == ClientAuth.NEED) {
sslSocket.setNeedClientAuth(true);
} else if (ssl.getClientAuth() == ClientAuth.WANT) {
sslSocket.setWantClientAuth(true);
}
if (ssl.getEnabledCipherSuites() != null) {
sslSocket.setEnabledCipherSuites(ssl
.getEnabledCipherSuites());
}
dataSoc = sslSocket;
} else {
LOG.debug("Opening passive data connection");
dataSoc = servSoc.accept();
}
DataConnectionConfiguration dataCfg = session.getListener()
.getDataConnectionConfiguration();
dataSoc.setSoTimeout(dataCfg.getIdleTime() * 1000);
LOG.debug("Passive data connection opened");
}
} catch (Exception ex) {
closeDataConnection();
LOG.warn("FtpDataConnection.getDataSocket()", ex);
throw ex;
}
dataSoc.setSoTimeout(dataConfig.getIdleTime() * 1000);
// Make sure we initiate the SSL handshake, or we'll
// get an error if we turn out not to send any data
// e.g. during the listing of an empty directory
if (dataSoc instanceof SSLSocket) {
((SSLSocket) dataSoc).startHandshake();
}
return dataSoc;
}
/*
* (non-Javadoc)
* Returns an InetAddress object from a hostname or IP address.
*/
private InetAddress resolveAddress(String host)
throws DataConnectionException {
if (host == null) {
return null;
} else {
try {
return InetAddress.getByName(host);
} catch (UnknownHostException ex) {
throw new DataConnectionException("Failed to resolve address", ex);
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.ftpserver.DataConnectionFactory#isSecure()
*/
public boolean isSecure() {
return secure;
}
/**
* Set the security protocol.
*/
public void setSecure(final boolean secure) {
this.secure = secure;
}
/*
* (non-Javadoc)
*
* @see org.apache.ftpserver.DataConnectionFactory#isZipMode()
*/
public boolean isZipMode() {
return isZip;
}
/**
* Set zip mode.
*/
public void setZipMode(final boolean zip) {
isZip = zip;
}
/**
* Check the data connection idle status.
*/
public synchronized boolean isTimeout(final long currTime) {
// data connection not requested - not a timeout
if (requestTime == 0L) {
return false;
}
// data connection active - not a timeout
if (dataSoc != null) {
return false;
}
// no idle time limit - not a timeout
int maxIdleTime = session.getListener()
.getDataConnectionConfiguration().getIdleTime() * 1000;
if (maxIdleTime == 0) {
return false;
}
// idle time is within limit - not a timeout
if ((currTime - requestTime) < maxIdleTime) {
return false;
}
return true;
}
/**
* Dispose data connection - close all the sockets.
*/
public void dispose() {
closeDataConnection();
}
/**
* Sets the server's control address.
*/
public void setServerControlAddress(final InetAddress serverControlAddress) {
this.serverControlAddress = serverControlAddress;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/IODataConnectionFactory.java | Java | art | 15,650 |
/*
* 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.impl;
import org.apache.ftpserver.ftplet.FtpFile;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is the file related activity observer.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileObserver {
/**
* User file upload notification.
*/
void notifyUpload(FtpIoSession session, FtpFile file, long size);
/**
* User file download notification.
*/
void notifyDownload(FtpIoSession session, FtpFile file, long size);
/**
* User file delete notification.
*/
void notifyDelete(FtpIoSession session, FtpFile file);
/**
* User make directory notification.
*/
void notifyMkdir(FtpIoSession session, FtpFile file);
/**
* User remove directory notification.
*/
void notifyRmdir(FtpIoSession session, FtpFile file);
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/FileObserver.java | Java | art | 1,713 |
/*
* 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.impl;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Provides support for parsing a passive ports string as well as keeping track
* of reserved passive ports.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class PassivePorts {
private static final int MAX_PORT = 65535;
private int[] passivePorts;
private boolean[] reservedPorts;
private String passivePortsString;
private boolean checkIfBound;
/**
* Parse a string containing passive ports
*
* @param portsString
* A string of passive ports, can contain a single port (as an
* integer), multiple ports seperated by commas (e.g.
* 123,124,125) or ranges of ports, including open ended ranges
* (e.g. 123-125, 30000-, -1023). Combinations for single ports
* and ranges is also supported.
* @return An instance of {@link PassivePorts} based on the parsed string
* @throws IllegalArgumentException
* If any of of the ports in the string is invalid (e.g. not an
* integer or too large for a port number)
*/
private static int[] parse(final String portsString) {
List<Integer> passivePortsList = new ArrayList<Integer>();
boolean inRange = false;
Integer lastPort = 1;
StringTokenizer st = new StringTokenizer(portsString, ",;-", true);
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (",".equals(token) || ";".equals(token)) {
if (inRange) {
fillRange(passivePortsList, lastPort, MAX_PORT);
}
// reset state
lastPort = 1;
inRange = false;
} else if ("-".equals(token)) {
inRange = true;
} else if (token.length() == 0) {
// ignore whitespace
} else {
Integer port = Integer.valueOf(token);
verifyPort(port.intValue());
if (inRange) {
// add all numbers from last int
fillRange(passivePortsList, lastPort, port);
inRange = false;
}
addPort(passivePortsList, port);
lastPort = port;
}
}
if (inRange) {
fillRange(passivePortsList, lastPort, MAX_PORT);
}
int[] passivePorts = new int[passivePortsList.size()];
Iterator<Integer> iter = passivePortsList.iterator();
int counter = 0;
while (iter.hasNext()) {
Integer port = iter.next();
passivePorts[counter] = port.intValue();
counter++;
}
return passivePorts;
}
/**
* Fill a range of ports
*/
private static void fillRange(final List<Integer> passivePortsList,
final Integer beginPort, final Integer endPort) {
for (int i = beginPort.intValue(); i <= endPort.intValue(); i++) {
addPort(passivePortsList, i);
}
}
/**
* Add a single port if not already in list
*/
private static void addPort(final List<Integer> passivePortsList,
final Integer rangePort) {
if (!passivePortsList.contains(rangePort)) {
passivePortsList.add(rangePort);
}
}
/**
* Verify that the port is within the range of allowed ports
*/
private static void verifyPort(final int port) {
if (port < 0) {
throw new IllegalArgumentException("Port can not be negative: "
+ port);
} else if (port > MAX_PORT) {
throw new IllegalArgumentException("Port too large: " + port);
}
}
public PassivePorts(final String passivePorts, boolean checkIfBound) {
this(parse(passivePorts), checkIfBound);
this.passivePortsString = passivePorts;
}
public PassivePorts(final int[] passivePorts, boolean checkIfBound) {
if (passivePorts != null) {
this.passivePorts = passivePorts.clone();
} else {
this.passivePorts = null;
}
reservedPorts = new boolean[passivePorts.length];
this.checkIfBound = checkIfBound;
}
/**
* Checks that the port of not bound by another application
*/
private boolean checkPortUnbound(int port) {
// is this check disabled?
if(!checkIfBound) {
return true;
}
// if using 0 port, it will always be available
if(port == 0) {
return true;
}
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
return true;
} catch (IOException e) {
// port probably in use, check next
return false;
} finally {
if(ss != null) {
try {
ss.close();
} catch (IOException e) {
// could not close, check next
return false;
}
}
}
}
public int reserveNextPort() {
// search for a free port
for (int i = 0; i < passivePorts.length; i++) {
if (!reservedPorts[i] && checkPortUnbound(passivePorts[i])) {
if (passivePorts[i] != 0) {
reservedPorts[i] = true;
}
return passivePorts[i];
}
}
return -1;
}
public void releasePort(final int port) {
for (int i = 0; i < passivePorts.length; i++) {
if (passivePorts[i] == port) {
reservedPorts[i] = false;
break;
}
}
}
@Override
public String toString() {
if (passivePortsString != null) {
return passivePortsString;
} else {
StringBuffer sb = new StringBuffer();
for (int port : passivePorts) {
sb.append(port);
sb.append(",");
}
// remove the last ,
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
} | zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/PassivePorts.java | Java | art | 7,361 |
/*
* 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.impl;
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import org.apache.ftpserver.command.Command;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftpletcontainer.FtpletContainer;
import org.apache.ftpserver.listener.Listener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.write.WriteToClosedSessionException;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class DefaultFtpHandler implements FtpHandler {
private final Logger LOG = LoggerFactory.getLogger(DefaultFtpHandler.class);
private final static String[] NON_AUTHENTICATED_COMMANDS = new String[] {
"USER", "PASS", "AUTH", "QUIT", "PROT", "PBSZ" };
private FtpServerContext context;
private Listener listener;
public void init(final FtpServerContext context, final Listener listener) {
this.context = context;
this.listener = listener;
}
public void sessionCreated(final FtpIoSession session) throws Exception {
session.setListener(listener);
ServerFtpStatistics stats = ((ServerFtpStatistics) context
.getFtpStatistics());
if (stats != null) {
stats.setOpenConnection(session);
}
}
public void sessionOpened(final FtpIoSession session) throws Exception {
FtpletContainer ftplets = context.getFtpletContainer();
FtpletResult ftpletRet;
try {
ftpletRet = ftplets.onConnect(session.getFtpletSession());
} catch (Exception e) {
LOG.debug("Ftplet threw exception", e);
ftpletRet = FtpletResult.DISCONNECT;
}
if (ftpletRet == FtpletResult.DISCONNECT) {
LOG.debug("Ftplet returned DISCONNECT, session will be closed");
session.close(false).awaitUninterruptibly(10000);
} else {
session.updateLastAccessTime();
session.write(LocalizedFtpReply.translate(session, null, context,
FtpReply.REPLY_220_SERVICE_READY, null, null));
}
}
public void sessionClosed(final FtpIoSession session) throws Exception {
LOG.debug("Closing session");
try {
context.getFtpletContainer().onDisconnect(
session.getFtpletSession());
} catch (Exception e) {
// swallow the exception, we're closing down the session anyways
LOG.warn("Ftplet threw an exception on disconnect", e);
}
// make sure we close the data connection if it happens to be open
try {
ServerDataConnectionFactory dc = session.getDataConnection();
if(dc != null) {
dc.closeDataConnection();
}
} catch (Exception e) {
// swallow the exception, we're closing down the session anyways
LOG.warn("Data connection threw an exception on disconnect", e);
}
FileSystemView fs = session.getFileSystemView();
if(fs != null) {
try {
fs.dispose();
} catch (Exception e) {
LOG.warn("FileSystemView threw an exception on disposal", e);
}
}
ServerFtpStatistics stats = ((ServerFtpStatistics) context
.getFtpStatistics());
if (stats != null) {
stats.setLogout(session);
stats.setCloseConnection(session);
LOG.debug("Statistics login and connection count decreased due to session close");
} else {
LOG.warn("Statistics not available in session, can not decrease login and connection count");
}
LOG.debug("Session closed");
}
public void exceptionCaught(final FtpIoSession session,
final Throwable cause) throws Exception {
if(cause instanceof ProtocolDecoderException &&
cause.getCause() instanceof MalformedInputException) {
// client probably sent something which is not UTF-8 and we failed to
// decode it
LOG.warn(
"Client sent command that could not be decoded: {}",
((ProtocolDecoderException)cause).getHexdump());
session.write(new DefaultFtpReply(FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "Invalid character in command"));
} else if (cause instanceof WriteToClosedSessionException) {
WriteToClosedSessionException writeToClosedSessionException =
(WriteToClosedSessionException) cause;
LOG.warn(
"Client closed connection before all replies could be sent, last reply was {}",
writeToClosedSessionException.getRequest());
session.close(false).awaitUninterruptibly(10000);
} else {
LOG.error("Exception caught, closing session", cause);
session.close(false).awaitUninterruptibly(10000);
}
}
private boolean isCommandOkWithoutAuthentication(String command) {
boolean okay = false;
for (String allowed : NON_AUTHENTICATED_COMMANDS) {
if (allowed.equals(command)) {
okay = true;
break;
}
}
return okay;
}
public void messageReceived(final FtpIoSession session,
final FtpRequest request) throws Exception {
try {
session.updateLastAccessTime();
String commandName = request.getCommand();
CommandFactory commandFactory = context.getCommandFactory();
Command command = commandFactory.getCommand(commandName);
// make sure the user is authenticated before he issues commands
if (!session.isLoggedIn()
&& !isCommandOkWithoutAuthentication(commandName)) {
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_530_NOT_LOGGED_IN,
"permission", null));
return;
}
FtpletContainer ftplets = context.getFtpletContainer();
FtpletResult ftpletRet;
try {
ftpletRet = ftplets.beforeCommand(session.getFtpletSession(),
request);
} catch (Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletResult.DISCONNECT;
}
if (ftpletRet == FtpletResult.DISCONNECT) {
LOG.debug("Ftplet returned DISCONNECT, session will be closed");
session.close(false).awaitUninterruptibly(10000);
return;
} else if (ftpletRet != FtpletResult.SKIP) {
if (command != null) {
synchronized (session) {
command.execute(session, context, request);
}
} else {
session.write(LocalizedFtpReply.translate(session, request,
context,
FtpReply.REPLY_502_COMMAND_NOT_IMPLEMENTED,
"not.implemented", null));
}
try {
ftpletRet = ftplets.afterCommand(
session.getFtpletSession(), request, session
.getLastReply());
} catch (Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletResult.DISCONNECT;
}
if (ftpletRet == FtpletResult.DISCONNECT) {
LOG.debug("Ftplet returned DISCONNECT, session will be closed");
session.close(false).awaitUninterruptibly(10000);
return;
}
}
} catch (Exception ex) {
// send error reply
try {
session.write(LocalizedFtpReply.translate(session, request,
context, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN,
null, null));
} catch (Exception ex1) {
}
if (ex instanceof java.io.IOException) {
throw (IOException) ex;
} else {
LOG.warn("RequestHandler.service()", ex);
}
}
}
public void sessionIdle(final FtpIoSession session, final IdleStatus status)
throws Exception {
LOG.info("Session idle, closing");
session.close(false).awaitUninterruptibly(10000);
}
public void messageSent(final FtpIoSession session, final FtpReply reply)
throws Exception {
// do nothing
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpHandler.java | Java | art | 10,162 |
/*
* 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.impl;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.User;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is FTP statistics implementation.
*
* TODO revisit concurrency, right now we're a bit over zealous with both Atomic*
* counters and synchronization
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpStatistics implements ServerFtpStatistics {
private StatisticsObserver observer = null;
private FileObserver fileObserver = null;
private Date startTime = new Date();
private AtomicInteger uploadCount = new AtomicInteger(0);
private AtomicInteger downloadCount = new AtomicInteger(0);
private AtomicInteger deleteCount = new AtomicInteger(0);
private AtomicInteger mkdirCount = new AtomicInteger(0);
private AtomicInteger rmdirCount = new AtomicInteger(0);
private AtomicInteger currLogins = new AtomicInteger(0);
private AtomicInteger totalLogins = new AtomicInteger(0);
private AtomicInteger totalFailedLogins = new AtomicInteger(0);
private AtomicInteger currAnonLogins = new AtomicInteger(0);
private AtomicInteger totalAnonLogins = new AtomicInteger(0);
private AtomicInteger currConnections = new AtomicInteger(0);
private AtomicInteger totalConnections = new AtomicInteger(0);
private AtomicLong bytesUpload = new AtomicLong(0L);
private AtomicLong bytesDownload = new AtomicLong(0L);
private static class UserLogins {
private Map<InetAddress, AtomicInteger> perAddress = new ConcurrentHashMap<InetAddress, AtomicInteger>();
public UserLogins(InetAddress address) {
// init with the first connection
totalLogins = new AtomicInteger(1);
perAddress.put(address, new AtomicInteger(1));
}
public AtomicInteger loginsFromInetAddress(InetAddress address) {
AtomicInteger logins = perAddress.get(address);
if (logins == null) {
logins = new AtomicInteger(0);
perAddress.put(address, logins);
}
return logins;
}
public AtomicInteger totalLogins;
}
/**
*The user login information.
*/
private Map<String, UserLogins> userLoginTable = new ConcurrentHashMap<String, UserLogins>();
public static final String LOGIN_NUMBER = "login_number";
/**
* Set the observer.
*/
public void setObserver(final StatisticsObserver observer) {
this.observer = observer;
}
/**
* Set the file observer.
*/
public void setFileObserver(final FileObserver observer) {
fileObserver = observer;
}
// //////////////////////////////////////////////////////
// /////////////// All getter methods /////////////////
/**
* Get server start time.
*/
public Date getStartTime() {
if (startTime != null) {
return (Date) startTime.clone();
} else {
return null;
}
}
/**
* Get number of files uploaded.
*/
public int getTotalUploadNumber() {
return uploadCount.get();
}
/**
* Get number of files downloaded.
*/
public int getTotalDownloadNumber() {
return downloadCount.get();
}
/**
* Get number of files deleted.
*/
public int getTotalDeleteNumber() {
return deleteCount.get();
}
/**
* Get total number of bytes uploaded.
*/
public long getTotalUploadSize() {
return bytesUpload.get();
}
/**
* Get total number of bytes downloaded.
*/
public long getTotalDownloadSize() {
return bytesDownload.get();
}
/**
* Get total directory created.
*/
public int getTotalDirectoryCreated() {
return mkdirCount.get();
}
/**
* Get total directory removed.
*/
public int getTotalDirectoryRemoved() {
return rmdirCount.get();
}
/**
* Get total number of connections.
*/
public int getTotalConnectionNumber() {
return totalConnections.get();
}
/**
* Get current number of connections.
*/
public int getCurrentConnectionNumber() {
return currConnections.get();
}
/**
* Get total number of logins.
*/
public int getTotalLoginNumber() {
return totalLogins.get();
}
/**
* Get total failed login number.
*/
public int getTotalFailedLoginNumber() {
return totalFailedLogins.get();
}
/**
* Get current number of logins.
*/
public int getCurrentLoginNumber() {
return currLogins.get();
}
/**
* Get total number of anonymous logins.
*/
public int getTotalAnonymousLoginNumber() {
return totalAnonLogins.get();
}
/**
* Get current number of anonymous logins.
*/
public int getCurrentAnonymousLoginNumber() {
return currAnonLogins.get();
}
/**
* Get the login number for the specific user
*/
public synchronized int getCurrentUserLoginNumber(final User user) {
UserLogins userLogins = userLoginTable.get(user.getName());
if (userLogins == null) {// not found the login user's statistics info
return 0;
} else {
return userLogins.totalLogins.get();
}
}
/**
* Get the login number for the specific user from the ipAddress
*
* @param user
* login user account
* @param ipAddress
* the ip address of the remote user
*/
public synchronized int getCurrentUserLoginNumber(final User user,
final InetAddress ipAddress) {
UserLogins userLogins = userLoginTable.get(user.getName());
if (userLogins == null) {// not found the login user's statistics info
return 0;
} else {
return userLogins.loginsFromInetAddress(ipAddress).get();
}
}
// //////////////////////////////////////////////////////
// /////////////// All setter methods /////////////////
/**
* Increment upload count.
*/
public synchronized void setUpload(final FtpIoSession session,
final FtpFile file, final long size) {
uploadCount.incrementAndGet();
bytesUpload.addAndGet(size);
notifyUpload(session, file, size);
}
/**
* Increment download count.
*/
public synchronized void setDownload(final FtpIoSession session,
final FtpFile file, final long size) {
downloadCount.incrementAndGet();
bytesDownload.addAndGet(size);
notifyDownload(session, file, size);
}
/**
* Increment delete count.
*/
public synchronized void setDelete(final FtpIoSession session,
final FtpFile file) {
deleteCount.incrementAndGet();
notifyDelete(session, file);
}
/**
* Increment make directory count.
*/
public synchronized void setMkdir(final FtpIoSession session,
final FtpFile file) {
mkdirCount.incrementAndGet();
notifyMkdir(session, file);
}
/**
* Increment remove directory count.
*/
public synchronized void setRmdir(final FtpIoSession session,
final FtpFile file) {
rmdirCount.incrementAndGet();
notifyRmdir(session, file);
}
/**
* Increment open connection count.
*/
public synchronized void setOpenConnection(final FtpIoSession session) {
currConnections.incrementAndGet();
totalConnections.incrementAndGet();
notifyOpenConnection(session);
}
/**
* Decrement open connection count.
*/
public synchronized void setCloseConnection(final FtpIoSession session) {
if (currConnections.get() > 0) {
currConnections.decrementAndGet();
}
notifyCloseConnection(session);
}
/**
* New login.
*/
public synchronized void setLogin(final FtpIoSession session) {
currLogins.incrementAndGet();
totalLogins.incrementAndGet();
User user = session.getUser();
if ("anonymous".equals(user.getName())) {
currAnonLogins.incrementAndGet();
totalAnonLogins.incrementAndGet();
}
synchronized (user) {// thread safety is needed. Since the login occurrs
// at low frequency, this overhead is endurable
UserLogins statisticsTable = userLoginTable.get(user.getName());
if (statisticsTable == null) {
// the hash table that records the login information of the user
// and its ip address.
InetAddress address = null;
if (session.getRemoteAddress() instanceof InetSocketAddress) {
address = ((InetSocketAddress) session.getRemoteAddress())
.getAddress();
}
statisticsTable = new UserLogins(address);
userLoginTable.put(user.getName(), statisticsTable);
} else {
statisticsTable.totalLogins.incrementAndGet();
if (session.getRemoteAddress() instanceof InetSocketAddress) {
InetAddress address = ((InetSocketAddress) session
.getRemoteAddress()).getAddress();
statisticsTable.loginsFromInetAddress(address)
.incrementAndGet();
}
}
}
notifyLogin(session);
}
/**
* Increment failed login count.
*/
public synchronized void setLoginFail(final FtpIoSession session) {
totalFailedLogins.incrementAndGet();
notifyLoginFail(session);
}
/**
* User logout
*/
public synchronized void setLogout(final FtpIoSession session) {
User user = session.getUser();
if (user == null) {
return;
}
currLogins.decrementAndGet();
if ("anonymous".equals(user.getName())) {
currAnonLogins.decrementAndGet();
}
synchronized (user) {
UserLogins userLogins = userLoginTable.get(user.getName());
if (userLogins != null) {
userLogins.totalLogins.decrementAndGet();
if (session.getRemoteAddress() instanceof InetSocketAddress) {
InetAddress address = ((InetSocketAddress) session
.getRemoteAddress()).getAddress();
userLogins.loginsFromInetAddress(address).decrementAndGet();
}
}
}
notifyLogout(session);
}
// //////////////////////////////////////////////////////////
// /////////////// all observer methods ////////////////////
/**
* Observer upload notification.
*/
private void notifyUpload(final FtpIoSession session,
final FtpFile file, long size) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyUpload();
}
FileObserver fileObserver = this.fileObserver;
if (fileObserver != null) {
fileObserver.notifyUpload(session, file, size);
}
}
/**
* Observer download notification.
*/
private void notifyDownload(final FtpIoSession session,
final FtpFile file, final long size) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyDownload();
}
FileObserver fileObserver = this.fileObserver;
if (fileObserver != null) {
fileObserver.notifyDownload(session, file, size);
}
}
/**
* Observer delete notification.
*/
private void notifyDelete(final FtpIoSession session, final FtpFile file) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyDelete();
}
FileObserver fileObserver = this.fileObserver;
if (fileObserver != null) {
fileObserver.notifyDelete(session, file);
}
}
/**
* Observer make directory notification.
*/
private void notifyMkdir(final FtpIoSession session, final FtpFile file) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyMkdir();
}
FileObserver fileObserver = this.fileObserver;
if (fileObserver != null) {
fileObserver.notifyMkdir(session, file);
}
}
/**
* Observer remove directory notification.
*/
private void notifyRmdir(final FtpIoSession session, final FtpFile file) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyRmdir();
}
FileObserver fileObserver = this.fileObserver;
if (fileObserver != null) {
fileObserver.notifyRmdir(session, file);
}
}
/**
* Observer open connection notification.
*/
private void notifyOpenConnection(final FtpIoSession session) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyOpenConnection();
}
}
/**
* Observer close connection notification.
*/
private void notifyCloseConnection(final FtpIoSession session) {
StatisticsObserver observer = this.observer;
if (observer != null) {
observer.notifyCloseConnection();
}
}
/**
* Observer login notification.
*/
private void notifyLogin(final FtpIoSession session) {
StatisticsObserver observer = this.observer;
if (observer != null) {
// is anonymous login
User user = session.getUser();
boolean anonymous = false;
if (user != null) {
String login = user.getName();
anonymous = (login != null) && login.equals("anonymous");
}
observer.notifyLogin(anonymous);
}
}
/**
* Observer failed login notification.
*/
private void notifyLoginFail(final FtpIoSession session) {
StatisticsObserver observer = this.observer;
if (observer != null) {
if (session.getRemoteAddress() instanceof InetSocketAddress) {
observer.notifyLoginFail(((InetSocketAddress) session
.getRemoteAddress()).getAddress());
}
}
}
/**
* Observer logout notification.
*/
private void notifyLogout(final FtpIoSession session) {
StatisticsObserver observer = this.observer;
if (observer != null) {
// is anonymous login
User user = session.getUser();
boolean anonymous = false;
if (user != null) {
String login = user.getName();
anonymous = (login != null) && login.equals("anonymous");
}
observer.notifyLogout(anonymous);
}
}
/**
* Reset the cumulative counters.
*/
public synchronized void resetStatisticsCounters() {
startTime = new Date();
uploadCount.set(0);
downloadCount.set(0);
deleteCount.set(0);
mkdirCount.set(0);
rmdirCount.set(0);
totalLogins.set(0);
totalFailedLogins.set(0);
totalAnonLogins.set(0);
totalConnections.set(0);
bytesUpload.set(0);
bytesDownload.set(0);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpStatistics.java | Java | art | 16,804 |
/*
* 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.impl;
import org.apache.ftpserver.ftplet.FtpRequest;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FTP request object.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpRequest implements FtpRequest {
private String line;
private String command;
private String argument;
/**
* Default constructor.
*/
public DefaultFtpRequest(final String requestLine) {
parse(requestLine);
}
/**
* Parse the ftp command line.
*/
private void parse(final String lineToParse) {
// parse request
line = lineToParse.trim();
command = null;
argument = null;
int spInd = line.indexOf(' ');
if (spInd != -1) {
argument = line.substring(spInd + 1);
if (argument.equals("")) {
argument = null;
}
command = line.substring(0, spInd).toUpperCase();
} else {
command = line.toUpperCase();
}
if ((command.length() > 0) && (command.charAt(0) == 'X')) {
command = command.substring(1);
}
}
/**
* Get the ftp command.
*/
public String getCommand() {
return command;
}
/**
* Get ftp input argument.
*/
public String getArgument() {
return argument;
}
/**
* Get the ftp request line.
*/
public String getRequestLine() {
return line;
}
/**
* Has argument.
*/
public boolean hasArgument() {
return getArgument() != null;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return getRequestLine();
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpRequest.java | Java | art | 2,615 |
/*
* 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.impl;
import java.net.InetAddress;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FTP statistics observer interface.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface StatisticsObserver {
/**
* User file upload notification.
*/
void notifyUpload();
/**
* User file download notification.
*/
void notifyDownload();
/**
* User file delete notification.
*/
void notifyDelete();
/**
* User make directory notification.
*/
void notifyMkdir();
/**
* User remove directory notification.
*/
void notifyRmdir();
/**
* New user login notification.
*/
void notifyLogin(boolean anonymous);
/**
* Failed user login notification.
*
* @param address
* Remote address that the failure came from
*/
void notifyLoginFail(InetAddress address);
/**
* User logout notification.
*/
void notifyLogout(boolean anonymous);
/**
* Connection open notification
*/
void notifyOpenConnection();
/**
* Connection close notification
*/
void notifyCloseConnection();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/StatisticsObserver.java | Java | art | 2,056 |
/*
* 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.impl;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpStatistics;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is same as <code>org.apache.ftpserver.ftplet.FtpStatistics</code> with
* added observer and setting values functionalities.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface ServerFtpStatistics extends FtpStatistics {
/**
* Set statistics observer.
*/
void setObserver(StatisticsObserver observer);
/**
* Set file observer.
*/
void setFileObserver(FileObserver observer);
/**
* Increment upload count.
*/
void setUpload(FtpIoSession session, FtpFile file, long size);
/**
* Increment download count.
*/
void setDownload(FtpIoSession session, FtpFile file, long size);
/**
* Increment make directory count.
*/
void setMkdir(FtpIoSession session, FtpFile dir);
/**
* Decrement remove directory count.
*/
void setRmdir(FtpIoSession session, FtpFile dir);
/**
* Increment delete count.
*/
void setDelete(FtpIoSession session, FtpFile file);
/**
* Increment current connection count.
*/
void setOpenConnection(FtpIoSession session);
/**
* Decrement close connection count.
*/
void setCloseConnection(FtpIoSession session);
/**
* Increment current login count.
*/
void setLogin(FtpIoSession session);
/**
* Increment failed login count.
*/
void setLoginFail(FtpIoSession session);
/**
* Decrement current login count.
*/
void setLogout(FtpIoSession session);
/**
* Reset all cumulative total counters. Do not reset current counters, like
* current logins, otherwise these will become negative when someone
* disconnects.
*/
void resetStatisticsCounters();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/ServerFtpStatistics.java | Java | art | 2,764 |
/*
* 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.impl;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.cert.Certificate;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import org.apache.ftpserver.ftplet.DataType;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.Structure;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.listener.Listener;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.TransportMetadata;
import org.apache.mina.core.session.AbstractIoSession;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.write.WriteRequestQueue;
import org.apache.mina.filter.ssl.SslFilter;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class FtpIoSession implements IoSession {
/**
* Contains user name between USER and PASS commands
*/
public static final String ATTRIBUTE_PREFIX = "org.apache.ftpserver.";
private static final String ATTRIBUTE_USER_ARGUMENT = ATTRIBUTE_PREFIX
+ "user-argument";
private static final String ATTRIBUTE_SESSION_ID = ATTRIBUTE_PREFIX
+ "session-id";
private static final String ATTRIBUTE_USER = ATTRIBUTE_PREFIX + "user";
private static final String ATTRIBUTE_LANGUAGE = ATTRIBUTE_PREFIX
+ "language";
private static final String ATTRIBUTE_LOGIN_TIME = ATTRIBUTE_PREFIX
+ "login-time";
private static final String ATTRIBUTE_DATA_CONNECTION = ATTRIBUTE_PREFIX
+ "data-connection";
private static final String ATTRIBUTE_FILE_SYSTEM = ATTRIBUTE_PREFIX
+ "file-system";
private static final String ATTRIBUTE_RENAME_FROM = ATTRIBUTE_PREFIX
+ "rename-from";
private static final String ATTRIBUTE_FILE_OFFSET = ATTRIBUTE_PREFIX
+ "file-offset";
private static final String ATTRIBUTE_DATA_TYPE = ATTRIBUTE_PREFIX
+ "data-type";
private static final String ATTRIBUTE_STRUCTURE = ATTRIBUTE_PREFIX
+ "structure";
private static final String ATTRIBUTE_FAILED_LOGINS = ATTRIBUTE_PREFIX
+ "failed-logins";
private static final String ATTRIBUTE_LISTENER = ATTRIBUTE_PREFIX
+ "listener";
private static final String ATTRIBUTE_MAX_IDLE_TIME = ATTRIBUTE_PREFIX
+ "max-idle-time";
private static final String ATTRIBUTE_LAST_ACCESS_TIME = ATTRIBUTE_PREFIX
+ "last-access-time";
private static final String ATTRIBUTE_CACHED_REMOTE_ADDRESS = ATTRIBUTE_PREFIX
+ "cached-remote-address";
private IoSession wrappedSession;
private FtpServerContext context;
/**
* Last reply that was sent to the client, if any.
*/
private FtpReply lastReply = null;
/* Begin wrapped IoSession methods */
/**
* @see IoSession#close()
*/
public CloseFuture close() {
return wrappedSession.close();
}
/**
* @see IoSession#close(boolean)
*/
public CloseFuture close(boolean immediately) {
return wrappedSession.close(immediately);
}
/**
* @see IoSession#containsAttribute(Object)
*/
public boolean containsAttribute(Object key) {
return wrappedSession.containsAttribute(key);
}
/**
* @see IoSession#getAttachment()
*/
@SuppressWarnings("deprecation")
public Object getAttachment() {
return wrappedSession.getAttachment();
}
/**
* @see IoSession#getAttribute(Object)
*/
public Object getAttribute(Object key) {
return wrappedSession.getAttribute(key);
}
/**
* @see IoSession#getAttribute(Object, Object)
*/
public Object getAttribute(Object key, Object defaultValue) {
return wrappedSession.getAttribute(key, defaultValue);
}
/**
* @see IoSession#getAttributeKeys()
*/
public Set<Object> getAttributeKeys() {
return wrappedSession.getAttributeKeys();
}
/**
* @see IoSession#getBothIdleCount()
*/
public int getBothIdleCount() {
return wrappedSession.getBothIdleCount();
}
/**
* @see IoSession#getCloseFuture()
*/
public CloseFuture getCloseFuture() {
return wrappedSession.getCloseFuture();
}
/**
* @see IoSession#getConfig()
*/
public IoSessionConfig getConfig() {
return wrappedSession.getConfig();
}
/**
* @see IoSession#getCreationTime()
*/
public long getCreationTime() {
return wrappedSession.getCreationTime();
}
/**
* @see IoSession#getFilterChain()
*/
public IoFilterChain getFilterChain() {
return wrappedSession.getFilterChain();
}
/**
* @see IoSession#getHandler()
*/
public IoHandler getHandler() {
return wrappedSession.getHandler();
}
/**
* @see IoSession#getId()
*/
public long getId() {
return wrappedSession.getId();
}
/**
* @see IoSession#getIdleCount(IdleStatus)
*/
public int getIdleCount(IdleStatus status) {
return wrappedSession.getIdleCount(status);
}
/**
* @see IoSession#getLastBothIdleTime()
*/
public long getLastBothIdleTime() {
return wrappedSession.getLastBothIdleTime();
}
/**
* @see IoSession#getLastIdleTime(IdleStatus)
*/
public long getLastIdleTime(IdleStatus status) {
return wrappedSession.getLastIdleTime(status);
}
/**
* @see IoSession#getLastIoTime()
*/
public long getLastIoTime() {
return wrappedSession.getLastIoTime();
}
/**
* @see IoSession#getLastReadTime()
*/
public long getLastReadTime() {
return wrappedSession.getLastReadTime();
}
/**
* @see IoSession#getLastReaderIdleTime()
*/
public long getLastReaderIdleTime() {
return wrappedSession.getLastReaderIdleTime();
}
/**
* @see IoSession#getLastWriteTime()
*/
public long getLastWriteTime() {
return wrappedSession.getLastWriteTime();
}
/**
* @see IoSession#getLastWriterIdleTime()
*/
public long getLastWriterIdleTime() {
return wrappedSession.getLastWriterIdleTime();
}
/**
* @see IoSession#getLocalAddress()
*/
public SocketAddress getLocalAddress() {
return wrappedSession.getLocalAddress();
}
/**
* @see IoSession#getReadBytes()
*/
public long getReadBytes() {
return wrappedSession.getReadBytes();
}
/**
* @see IoSession#getReadBytesThroughput()
*/
public double getReadBytesThroughput() {
return wrappedSession.getReadBytesThroughput();
}
/**
* @see IoSession#getReadMessages()
*/
public long getReadMessages() {
return wrappedSession.getReadMessages();
}
/**
* @see IoSession#getReadMessagesThroughput()
*/
public double getReadMessagesThroughput() {
return wrappedSession.getReadMessagesThroughput();
}
/**
* @see IoSession#getReaderIdleCount()
*/
public int getReaderIdleCount() {
return wrappedSession.getReaderIdleCount();
}
/**
* @see IoSession#getRemoteAddress()
*/
public SocketAddress getRemoteAddress() {
// when closing a socket, the remote address might be reset to null
// therefore, we attempt to keep a cached copy around
SocketAddress address = wrappedSession.getRemoteAddress();
if (address == null
&& containsAttribute(ATTRIBUTE_CACHED_REMOTE_ADDRESS)) {
return (SocketAddress) getAttribute(ATTRIBUTE_CACHED_REMOTE_ADDRESS);
} else {
setAttribute(ATTRIBUTE_CACHED_REMOTE_ADDRESS, address);
return address;
}
}
/**
* @see IoSession#getScheduledWriteBytes()
*/
public long getScheduledWriteBytes() {
return wrappedSession.getScheduledWriteBytes();
}
/**
* @see IoSession#getScheduledWriteMessages()
*/
public int getScheduledWriteMessages() {
return wrappedSession.getScheduledWriteMessages();
}
/**
* @see IoSession#getService()
*/
public IoService getService() {
return wrappedSession.getService();
}
/**
* @see IoSession#getServiceAddress()
*/
public SocketAddress getServiceAddress() {
return wrappedSession.getServiceAddress();
}
/**
* @see IoSession#getTransportMetadata()
*/
public TransportMetadata getTransportMetadata() {
return wrappedSession.getTransportMetadata();
}
/**
* @see IoSession#getWriterIdleCount()
*/
public int getWriterIdleCount() {
return wrappedSession.getWriterIdleCount();
}
/**
* @see IoSession#getWrittenBytes()
*/
public long getWrittenBytes() {
return wrappedSession.getWrittenBytes();
}
/**
* @see IoSession#getWrittenBytesThroughput()
*/
public double getWrittenBytesThroughput() {
return wrappedSession.getWrittenBytesThroughput();
}
/**
* @see IoSession#getWrittenMessages()
*/
public long getWrittenMessages() {
return wrappedSession.getWrittenMessages();
}
/**
* @see IoSession#getWrittenMessagesThroughput()
*/
public double getWrittenMessagesThroughput() {
return wrappedSession.getWrittenMessagesThroughput();
}
/**
* @see IoSession#isClosing()
*/
public boolean isClosing() {
return wrappedSession.isClosing();
}
/**
* @see IoSession#isConnected()
*/
public boolean isConnected() {
return wrappedSession.isConnected();
}
/**
* @see IoSession#isIdle(IdleStatus)
*/
public boolean isIdle(IdleStatus status) {
return wrappedSession.isIdle(status);
}
/**
* @see IoSession#read()
*/
public ReadFuture read() {
return wrappedSession.read();
}
/**
* @see IoSession#removeAttribute(Object)
*/
public Object removeAttribute(Object key) {
return wrappedSession.removeAttribute(key);
}
/**
* @see IoSession#removeAttribute(Object, Object)
*/
public boolean removeAttribute(Object key, Object value) {
return wrappedSession.removeAttribute(key, value);
}
/**
* @see IoSession#replaceAttribute(Object, Object, Object)
*/
public boolean replaceAttribute(Object key, Object oldValue, Object newValue) {
return wrappedSession.replaceAttribute(key, oldValue, newValue);
}
/**
* @see IoSession#resumeRead()
*/
public void resumeRead() {
wrappedSession.resumeRead();
}
/**
* @see IoSession#resumeWrite()
*/
public void resumeWrite() {
wrappedSession.resumeWrite();
}
/**
* @see IoSession#setAttachment(Object)
*/
@SuppressWarnings("deprecation")
public Object setAttachment(Object attachment) {
return wrappedSession.setAttachment(attachment);
}
/**
* @see IoSession#setAttribute(Object)
*/
public Object setAttribute(Object key) {
return wrappedSession.setAttribute(key);
}
/**
* @see IoSession#setAttribute(Object, Object)
*/
public Object setAttribute(Object key, Object value) {
return wrappedSession.setAttribute(key, value);
}
/**
* @see IoSession#setAttributeIfAbsent(Object)
*/
public Object setAttributeIfAbsent(Object key) {
return wrappedSession.setAttributeIfAbsent(key);
}
/**
* @see IoSession#setAttributeIfAbsent(Object, Object)
*/
public Object setAttributeIfAbsent(Object key, Object value) {
return wrappedSession.setAttributeIfAbsent(key, value);
}
/**
* @see IoSession#suspendRead()
*/
public void suspendRead() {
wrappedSession.suspendRead();
}
/**
* @see IoSession#suspendWrite()
*/
public void suspendWrite() {
wrappedSession.suspendWrite();
}
/**
* @see IoSession#write(Object)
*/
public WriteFuture write(Object message) {
WriteFuture future = wrappedSession.write(message);
this.lastReply = (FtpReply) message;
return future;
}
/**
* @see IoSession#write(Object, SocketAddress)
*/
public WriteFuture write(Object message, SocketAddress destination) {
WriteFuture future = wrappedSession.write(message, destination);
this.lastReply = (FtpReply) message;
return future;
}
/* End wrapped IoSession methods */
public void resetState() {
removeAttribute(ATTRIBUTE_RENAME_FROM);
removeAttribute(ATTRIBUTE_FILE_OFFSET);
}
public synchronized ServerDataConnectionFactory getDataConnection() {
if (containsAttribute(ATTRIBUTE_DATA_CONNECTION)) {
return (ServerDataConnectionFactory) getAttribute(ATTRIBUTE_DATA_CONNECTION);
} else {
IODataConnectionFactory dataCon = new IODataConnectionFactory(
context, this);
dataCon
.setServerControlAddress(((InetSocketAddress) getLocalAddress())
.getAddress());
setAttribute(ATTRIBUTE_DATA_CONNECTION, dataCon);
return dataCon;
}
}
public FileSystemView getFileSystemView() {
return (FileSystemView) getAttribute(ATTRIBUTE_FILE_SYSTEM);
}
public User getUser() {
return (User) getAttribute(ATTRIBUTE_USER);
}
/**
* Is logged-in
*/
public boolean isLoggedIn() {
return containsAttribute(ATTRIBUTE_USER);
}
public Listener getListener() {
return (Listener) getAttribute(ATTRIBUTE_LISTENER);
}
public void setListener(Listener listener) {
setAttribute(ATTRIBUTE_LISTENER, listener);
}
public FtpSession getFtpletSession() {
return new DefaultFtpSession(this);
}
public String getLanguage() {
return (String) getAttribute(ATTRIBUTE_LANGUAGE);
}
public void setLanguage(String language) {
setAttribute(ATTRIBUTE_LANGUAGE, language);
}
public String getUserArgument() {
return (String) getAttribute(ATTRIBUTE_USER_ARGUMENT);
}
public void setUser(User user) {
setAttribute(ATTRIBUTE_USER, user);
}
public void setUserArgument(String userArgument) {
setAttribute(ATTRIBUTE_USER_ARGUMENT, userArgument);
}
public int getMaxIdleTime() {
return (Integer) getAttribute(ATTRIBUTE_MAX_IDLE_TIME, 0);
}
public void setMaxIdleTime(int maxIdleTime) {
setAttribute(ATTRIBUTE_MAX_IDLE_TIME, maxIdleTime);
int listenerTimeout = getListener().getIdleTimeout();
// the listener timeout should be the upper limit, unless set to
// unlimited
// if the user limit is set to be unlimited, use the listener value is
// the threshold
// (already used as the default for all sessions)
// else, if the user limit is less than the listener idle time, use the
// user limit
if (listenerTimeout <= 0
|| (maxIdleTime > 0 && maxIdleTime < listenerTimeout)) {
wrappedSession.getConfig().setBothIdleTime(maxIdleTime);
}
}
public synchronized void increaseFailedLogins() {
int failedLogins = (Integer) getAttribute(ATTRIBUTE_FAILED_LOGINS, 0);
failedLogins++;
setAttribute(ATTRIBUTE_FAILED_LOGINS, failedLogins);
}
public int getFailedLogins() {
return (Integer) getAttribute(ATTRIBUTE_FAILED_LOGINS, 0);
}
public void setLogin(FileSystemView fsview) {
setAttribute(ATTRIBUTE_LOGIN_TIME, new Date());
setAttribute(ATTRIBUTE_FILE_SYSTEM, fsview);
}
public void reinitialize() {
logoutUser();
removeAttribute(ATTRIBUTE_USER);
removeAttribute(ATTRIBUTE_USER_ARGUMENT);
removeAttribute(ATTRIBUTE_LOGIN_TIME);
removeAttribute(ATTRIBUTE_FILE_SYSTEM);
removeAttribute(ATTRIBUTE_RENAME_FROM);
removeAttribute(ATTRIBUTE_FILE_OFFSET);
}
public void logoutUser() {
ServerFtpStatistics stats = ((ServerFtpStatistics) context
.getFtpStatistics());
if (stats != null) {
stats.setLogout(this);
LoggerFactory.getLogger(this.getClass()).debug(
"Statistics login decreased due to user logout");
} else {
LoggerFactory
.getLogger(this.getClass())
.warn(
"Statistics not available in session, can not decrease login count");
}
}
public void setFileOffset(long fileOffset) {
setAttribute(ATTRIBUTE_FILE_OFFSET, fileOffset);
}
public void setRenameFrom(FtpFile renFr) {
setAttribute(ATTRIBUTE_RENAME_FROM, renFr);
}
public FtpFile getRenameFrom() {
return (FtpFile) getAttribute(ATTRIBUTE_RENAME_FROM);
}
public long getFileOffset() {
return (Long) getAttribute(ATTRIBUTE_FILE_OFFSET, 0L);
}
public void setStructure(Structure structure) {
setAttribute(ATTRIBUTE_STRUCTURE, structure);
}
public void setDataType(DataType dataType) {
setAttribute(ATTRIBUTE_DATA_TYPE, dataType);
}
/**
* @see FtpSession#getSessionId()
*/
public UUID getSessionId() {
synchronized (wrappedSession) {
if (!wrappedSession.containsAttribute(ATTRIBUTE_SESSION_ID)) {
wrappedSession.setAttribute(ATTRIBUTE_SESSION_ID, UUID
.randomUUID());
}
return (UUID) wrappedSession.getAttribute(ATTRIBUTE_SESSION_ID);
}
}
public FtpIoSession(IoSession wrappedSession, FtpServerContext context) {
this.wrappedSession = wrappedSession;
this.context = context;
}
public Structure getStructure() {
return (Structure) getAttribute(ATTRIBUTE_STRUCTURE, Structure.FILE);
}
public DataType getDataType() {
return (DataType) getAttribute(ATTRIBUTE_DATA_TYPE, DataType.ASCII);
}
public Date getLoginTime() {
return (Date) getAttribute(ATTRIBUTE_LOGIN_TIME);
}
public Date getLastAccessTime() {
return (Date) getAttribute(ATTRIBUTE_LAST_ACCESS_TIME);
}
public Certificate[] getClientCertificates() {
if (getFilterChain().contains(SslFilter.class)) {
SslFilter sslFilter = (SslFilter) getFilterChain().get(
SslFilter.class);
SSLSession sslSession = sslFilter.getSslSession(this);
if (sslSession != null) {
try {
return sslSession.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
// ignore, certificate will not be available to the session
}
}
}
// no certificates available
return null;
}
public void updateLastAccessTime() {
setAttribute(ATTRIBUTE_LAST_ACCESS_TIME, new Date());
}
/**
* @see IoSession#getCurrentWriteMessage()
*/
public Object getCurrentWriteMessage() {
return wrappedSession.getCurrentWriteMessage();
}
/**
* @see IoSession#getCurrentWriteRequest()
*/
public WriteRequest getCurrentWriteRequest() {
return wrappedSession.getCurrentWriteRequest();
}
/**
* @see IoSession#isBothIdle()
*/
public boolean isBothIdle() {
return wrappedSession.isBothIdle();
}
/**
* @see IoSession#isReaderIdle()
*/
public boolean isReaderIdle() {
return wrappedSession.isReaderIdle();
}
/**
* @see IoSession#isWriterIdle()
*/
public boolean isWriterIdle() {
return wrappedSession.isWriterIdle();
}
/**
* Indicates whether the control socket for this session is secure, that is,
* running over SSL/TLS
*
* @return true if the control socket is secured
*/
public boolean isSecure() {
return getFilterChain().contains(SslFilter.class);
}
/**
* Increase the number of bytes written on the data connection
*
* @param increment
* The number of bytes written
*/
public void increaseWrittenDataBytes(int increment) {
if (wrappedSession instanceof AbstractIoSession) {
((AbstractIoSession) wrappedSession)
.increaseScheduledWriteBytes(increment);
((AbstractIoSession) wrappedSession).increaseWrittenBytes(
increment, System.currentTimeMillis());
}
}
/**
* Increase the number of bytes read on the data connection
*
* @param increment
* The number of bytes written
*/
public void increaseReadDataBytes(int increment) {
if (wrappedSession instanceof AbstractIoSession) {
((AbstractIoSession) wrappedSession).increaseReadBytes(increment,
System.currentTimeMillis());
}
}
/**
* Returns the last reply that was sent to the client.
*
* @return the last reply that was sent to the client.
*/
public FtpReply getLastReply() {
return lastReply;
}
/**
* @see IoSession#getWriteRequestQueue()
*/
public WriteRequestQueue getWriteRequestQueue() {
return wrappedSession.getWriteRequestQueue();
}
/**
* @see IoSession#isReadSuspended()
*/
public boolean isReadSuspended() {
return wrappedSession.isReadSuspended();
}
/**
* @see IoSession#isWriteSuspended()
*/
public boolean isWriteSuspended() {
return wrappedSession.isWriteSuspended();
}
/**
* @see IoSession#setCurrentWriteRequest(WriteRequest)
*/
public void setCurrentWriteRequest(WriteRequest currentWriteRequest) {
wrappedSession.setCurrentWriteRequest(currentWriteRequest);
}
/**
* @see IoSession#updateThroughput(long, boolean)
*/
public void updateThroughput(long currentTime, boolean force) {
wrappedSession.updateThroughput(currentTime, force);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/FtpIoSession.java | Java | art | 21,097 |
/*
* 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.impl;
import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.ssl.SslConfiguration;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Data connection configuration.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultDataConnectionConfiguration implements
DataConnectionConfiguration {
// maximum idle time in seconds
private int idleTime;
private SslConfiguration ssl;
private boolean activeEnabled;
private String activeLocalAddress;
private int activeLocalPort;
private boolean activeIpCheck;
private String passiveAddress;
private String passiveExternalAddress;
private PassivePorts passivePorts;
private final boolean implicitSsl;
/**
* Internal constructor, do not use directly. Use {@link DataConnectionConfigurationFactory} instead.
*/
public DefaultDataConnectionConfiguration(int idleTime,
SslConfiguration ssl, boolean activeEnabled, boolean activeIpCheck,
String activeLocalAddress, int activeLocalPort,
String passiveAddress, PassivePorts passivePorts,
String passiveExternalAddress, boolean implicitSsl) {
this.idleTime = idleTime;
this.ssl = ssl;
this.activeEnabled = activeEnabled;
this.activeIpCheck = activeIpCheck;
this.activeLocalAddress = activeLocalAddress;
this.activeLocalPort = activeLocalPort;
this.passiveAddress = passiveAddress;
this.passivePorts = passivePorts;
this.passiveExternalAddress = passiveExternalAddress;
this.implicitSsl = implicitSsl;
}
/**
* Get the maximum idle time in seconds.
*/
public int getIdleTime() {
return idleTime;
}
/**
* Is PORT enabled?
*/
public boolean isActiveEnabled() {
return activeEnabled;
}
/**
* Check the PORT IP?
*/
public boolean isActiveIpCheck() {
return activeIpCheck;
}
/**
* Get the local address for active mode data transfer.
*/
public String getActiveLocalAddress() {
return activeLocalAddress;
}
/**
* Get the active local port number.
*/
public int getActiveLocalPort() {
return activeLocalPort;
}
/**
* Get passive host.
*/
public String getPassiveAddress() {
return passiveAddress;
}
/**
* Get external passive host.
*/
public String getPassiveExernalAddress() {
return passiveExternalAddress;
}
/**
* Get passive data port. Data port number zero (0) means that any available
* port will be used.
*/
public synchronized int requestPassivePort() {
return passivePorts.reserveNextPort();
}
/**
* Retrive the passive ports configured for this data connection
*
* @return The String of passive ports
*/
public String getPassivePorts() {
return passivePorts.toString();
}
/**
* Release data port
*/
public synchronized void releasePassivePort(final int port) {
passivePorts.releasePort(port);
}
/**
* Get SSL component.
*/
public SslConfiguration getSslConfiguration() {
return ssl;
}
/**
* @see org.apache.ftpserver.DataConnectionConfiguration#isImplicitSsl()
*/
public boolean isImplicitSsl() {
return implicitSsl;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultDataConnectionConfiguration.java | Java | art | 4,391 |
/*
* 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.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.apache.ftpserver.ftplet.DataConnection;
import org.apache.ftpserver.ftplet.DataType;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.usermanager.impl.TransferRateRequest;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* An active open data connection, used for transfering data over the data
* connection.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IODataConnection implements DataConnection {
private final Logger LOG = LoggerFactory
.getLogger(IODataConnection.class);
private static final byte[] EOL = System.getProperty("line.separator").getBytes();
private FtpIoSession session;
private Socket socket;
private ServerDataConnectionFactory factory;
public IODataConnection(final Socket socket, final FtpIoSession session,
final ServerDataConnectionFactory factory) {
this.session = session;
this.socket = socket;
this.factory = factory;
}
/**
* Get data input stream. The return value will never be null.
*/
private InputStream getDataInputStream() throws IOException {
try {
// get data socket
Socket dataSoc = socket;
if (dataSoc == null) {
throw new IOException("Cannot open data connection.");
}
// create input stream
InputStream is = dataSoc.getInputStream();
if (factory.isZipMode()) {
is = new InflaterInputStream(is);
}
return is;
} catch (IOException ex) {
factory.closeDataConnection();
throw ex;
}
}
/**
* Get data output stream. The return value will never be null.
*/
private OutputStream getDataOutputStream() throws IOException {
try {
// get data socket
Socket dataSoc = socket;
if (dataSoc == null) {
throw new IOException("Cannot open data connection.");
}
// create output stream
OutputStream os = dataSoc.getOutputStream();
if (factory.isZipMode()) {
os = new DeflaterOutputStream(os);
}
return os;
} catch (IOException ex) {
factory.closeDataConnection();
throw ex;
}
}
/*
* (non-Javadoc)
*
* @seeorg.apache.ftpserver.FtpDataConnection2#transferFromClient(java.io.
* OutputStream)
*/
public final long transferFromClient(FtpSession session,
final OutputStream out) throws IOException {
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) session.getUser()
.authorize(transferRateRequest);
int maxRate = 0;
if (transferRateRequest != null) {
maxRate = transferRateRequest.getMaxUploadRate();
}
InputStream is = getDataInputStream();
try {
return transfer(session, false, is, out, maxRate);
} finally {
IoUtils.close(is);
}
}
/*
* (non-Javadoc)
*
* @see
* org.apache.ftpserver.FtpDataConnection2#transferToClient(java.io.InputStream
* )
*/
public final long transferToClient(FtpSession session, final InputStream in)
throws IOException {
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) session.getUser()
.authorize(transferRateRequest);
int maxRate = 0;
if (transferRateRequest != null) {
maxRate = transferRateRequest.getMaxDownloadRate();
}
OutputStream out = getDataOutputStream();
try {
return transfer(session, true, in, out, maxRate);
} finally {
IoUtils.close(out);
}
}
/*
* (non-Javadoc)
*
* @see
* org.apache.ftpserver.FtpDataConnection2#transferToClient(java.lang.String
* )
*/
public final void transferToClient(FtpSession session, final String str)
throws IOException {
OutputStream out = getDataOutputStream();
Writer writer = null;
try {
writer = new OutputStreamWriter(out, "UTF-8");
writer.write(str);
// update session
if (session instanceof DefaultFtpSession) {
((DefaultFtpSession) session).increaseWrittenDataBytes(str
.getBytes("UTF-8").length);
}
} finally {
if (writer != null) {
writer.flush();
}
IoUtils.close(writer);
}
}
private final long transfer(FtpSession session, boolean isWrite,
final InputStream in, final OutputStream out, final int maxRate)
throws IOException {
long transferredSize = 0L;
boolean isAscii = session.getDataType() == DataType.ASCII;
long startTime = System.currentTimeMillis();
byte[] buff = new byte[4096];
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = IoUtils.getBufferedInputStream(in);
bos = IoUtils.getBufferedOutputStream(out);
DefaultFtpSession defaultFtpSession = null;
if (session instanceof DefaultFtpSession) {
defaultFtpSession = (DefaultFtpSession) session;
}
byte lastByte = 0;
while (true) {
// if current rate exceeds the max rate, sleep for 50ms
// and again check the current transfer rate
if (maxRate > 0) {
// prevent "divide by zero" exception
long interval = System.currentTimeMillis() - startTime;
if (interval == 0) {
interval = 1;
}
// check current rate
long currRate = (transferredSize * 1000L) / interval;
if (currRate > maxRate) {
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
break;
}
continue;
}
}
// read data
int count = bis.read(buff);
if (count == -1) {
break;
}
// update MINA session
if (defaultFtpSession != null) {
if (isWrite) {
defaultFtpSession.increaseWrittenDataBytes(count);
} else {
defaultFtpSession.increaseReadDataBytes(count);
}
}
// write data
// if ascii, replace \n by \r\n
if (isAscii) {
for (int i = 0; i < count; ++i) {
byte b = buff[i];
if(isWrite) {
if (b == '\n' && lastByte != '\r') {
bos.write('\r');
}
bos.write(b);
} else {
if(b == '\n') {
// for reads, we should always get \r\n
// so what we do here is to ignore \n bytes
// and on \r dump the system local line ending
// Some clients won't transform new lines into \r\n so we make sure we don't delete new lines
if (lastByte != '\r'){
bos.write(EOL);
}
} else if(b == '\r') {
bos.write(EOL);
} else {
// not a line ending, just output
bos.write(b);
}
}
// store this byte so that we can compare it for line endings
lastByte = b;
}
} else {
bos.write(buff, 0, count);
}
transferredSize += count;
notifyObserver();
}
} catch(IOException e) {
LOG.warn("Exception during data transfer, closing data connection socket", e);
factory.closeDataConnection();
throw e;
} catch(RuntimeException e) {
LOG.warn("Exception during data transfer, closing data connection socket", e);
factory.closeDataConnection();
throw e;
} finally {
if (bos != null) {
bos.flush();
}
}
return transferredSize;
}
/**
* Notify connection manager observer.
*/
protected void notifyObserver() {
session.updateLastAccessTime();
// TODO this has been moved from AbstractConnection, do we need to keep
// it?
// serverContext.getConnectionManager().updateConnection(this);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/IODataConnection.java | Java | art | 10,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.impl;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftpletcontainer.FtpletContainer;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.message.MessageResource;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is basically <code>org.apache.ftpserver.ftplet.FtpletContext</code> with
* added connection manager, message resource functionalities.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FtpServerContext extends FtpletContext {
ConnectionConfig getConnectionConfig();
/**
* Get message resource.
*/
MessageResource getMessageResource();
/**
* Get ftplet container.
*/
FtpletContainer getFtpletContainer();
Listener getListener(String name);
Map<String, Listener> getListeners();
/**
* Get the command factory.
*/
CommandFactory getCommandFactory();
/**
* Release all components.
*/
void dispose();
/**
* Returns the thread pool executor for this context.
* @return the thread pool executor for this context.
*/
ThreadPoolExecutor getThreadPoolExecutor();
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/FtpServerContext.java | Java | art | 2,217 |
/*
* 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.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.ConnectionConfigFactory;
import org.apache.ftpserver.command.CommandFactory;
import org.apache.ftpserver.command.CommandFactoryFactory;
import org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpStatistics;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.ftpletcontainer.FtpletContainer;
import org.apache.ftpserver.ftpletcontainer.impl.DefaultFtpletContainer;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.message.MessageResource;
import org.apache.ftpserver.message.MessageResourceFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.TransferRatePermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.apache.mina.filter.executor.OrderedThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <strong>Internal class, do not use directly.</strong>
*
* FTP server configuration implementation. It holds all the components used.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DefaultFtpServerContext implements FtpServerContext {
private final Logger LOG = LoggerFactory
.getLogger(DefaultFtpServerContext.class);
private MessageResource messageResource = new MessageResourceFactory().createMessageResource();
private UserManager userManager = new PropertiesUserManagerFactory().createUserManager();
private FileSystemFactory fileSystemManager = new NativeFileSystemFactory();
private FtpletContainer ftpletContainer = new DefaultFtpletContainer();
private FtpStatistics statistics = new DefaultFtpStatistics();
private CommandFactory commandFactory = new CommandFactoryFactory().createCommandFactory();
private ConnectionConfig connectionConfig = new ConnectionConfigFactory().createConnectionConfig();
private Map<String, Listener> listeners = new HashMap<String, Listener>();
private static final List<Authority> ADMIN_AUTHORITIES = new ArrayList<Authority>();
private static final List<Authority> ANON_AUTHORITIES = new ArrayList<Authority>();
/**
* The thread pool executor to be used by the server using this context
*/
private ThreadPoolExecutor threadPoolExecutor = null;
static {
ADMIN_AUTHORITIES.add(new WritePermission());
ANON_AUTHORITIES.add(new ConcurrentLoginPermission(20, 2));
ANON_AUTHORITIES.add(new TransferRatePermission(4800, 4800));
}
public DefaultFtpServerContext() {
// create the default listener
listeners.put("default", new ListenerFactory().createListener());
}
/**
* Create default users.
*/
public void createDefaultUsers() throws Exception {
UserManager userManager = getUserManager();
// create admin user
String adminName = userManager.getAdminName();
if (!userManager.doesExist(adminName)) {
LOG.info("Creating user : " + adminName);
BaseUser adminUser = new BaseUser();
adminUser.setName(adminName);
adminUser.setPassword(adminName);
adminUser.setEnabled(true);
adminUser.setAuthorities(ADMIN_AUTHORITIES);
adminUser.setHomeDirectory("./res/home");
adminUser.setMaxIdleTime(0);
userManager.save(adminUser);
}
// create anonymous user
if (!userManager.doesExist("anonymous")) {
LOG.info("Creating user : anonymous");
BaseUser anonUser = new BaseUser();
anonUser.setName("anonymous");
anonUser.setPassword("");
anonUser.setAuthorities(ANON_AUTHORITIES);
anonUser.setEnabled(true);
anonUser.setHomeDirectory("./res/home");
anonUser.setMaxIdleTime(300);
userManager.save(anonUser);
}
}
/**
* Get user manager.
*/
public UserManager getUserManager() {
return userManager;
}
/**
* Get file system manager.
*/
public FileSystemFactory getFileSystemManager() {
return fileSystemManager;
}
/**
* Get message resource.
*/
public MessageResource getMessageResource() {
return messageResource;
}
/**
* Get ftp statistics.
*/
public FtpStatistics getFtpStatistics() {
return statistics;
}
public void setFtpStatistics(FtpStatistics statistics) {
this.statistics = statistics;
}
/**
* Get ftplet handler.
*/
public FtpletContainer getFtpletContainer() {
return ftpletContainer;
}
/**
* Get the command factory.
*/
public CommandFactory getCommandFactory() {
return commandFactory;
}
/**
* Get Ftplet.
*/
public Ftplet getFtplet(String name) {
return ftpletContainer.getFtplet(name);
}
/**
* Close all the components.
*/
public void dispose() {
listeners.clear();
ftpletContainer.getFtplets().clear();
if (threadPoolExecutor != null) {
LOG.debug("Shutting down the thread pool executor");
threadPoolExecutor.shutdown();
try {
threadPoolExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
} finally {
// TODO: how to handle?
}
}
}
public Listener getListener(String name) {
return listeners.get(name);
}
public void setListener(String name, Listener listener) {
listeners.put(name, listener);
}
public Map<String, Listener> getListeners() {
return listeners;
}
public void setListeners(Map<String, Listener> listeners) {
this.listeners = listeners;
}
public void addListener(String name, Listener listener) {
listeners.put(name, listener);
}
public Listener removeListener(String name) {
return listeners.remove(name);
}
public void setCommandFactory(CommandFactory commandFactory) {
this.commandFactory = commandFactory;
}
public void setFileSystemManager(FileSystemFactory fileSystemManager) {
this.fileSystemManager = fileSystemManager;
}
public void setFtpletContainer(FtpletContainer ftpletContainer) {
this.ftpletContainer = ftpletContainer;
}
public void setMessageResource(MessageResource messageResource) {
this.messageResource = messageResource;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public ConnectionConfig getConnectionConfig() {
return connectionConfig;
}
public void setConnectionConfig(ConnectionConfig connectionConfig) {
this.connectionConfig = connectionConfig;
}
public synchronized ThreadPoolExecutor getThreadPoolExecutor() {
if(threadPoolExecutor == null) {
int maxThreads = connectionConfig.getMaxThreads();
if(maxThreads < 1) {
int maxLogins = connectionConfig.getMaxLogins();
if(maxLogins > 0) {
maxThreads = maxLogins;
}
else {
maxThreads = 16;
}
}
LOG.debug("Intializing shared thread pool executor with max threads of {}", maxThreads);
threadPoolExecutor = new OrderedThreadPoolExecutor(maxThreads);
}
return threadPoolExecutor;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/impl/DefaultFtpServerContext.java | Java | art | 9,089 |
/*
* 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.util;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;
import org.apache.ftpserver.ftplet.FtpException;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This class encapsulates <code>java.util.Properties</code> to add java
* primitives and some other java classes.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class BaseProperties extends Properties {
private static final long serialVersionUID = 5572645129592131953L;
/**
* Default constructor.
*/
public BaseProperties() {
}
/**
* Load existing property.
*/
public BaseProperties(final Properties prop) {
super(prop);
}
// ////////////////////////////////////////
// ////// Properties Get Methods ////////
// ////////////////////////////////////////
/**
* Get boolean value.
*/
public boolean getBoolean(final String str) throws FtpException {
String prop = getProperty(str);
if (prop == null) {
throw new FtpException(str + " not found");
}
return prop.toLowerCase().equals("true");
}
public boolean getBoolean(final String str, final boolean bol) {
try {
return getBoolean(str);
} catch (FtpException ex) {
return bol;
}
}
/**
* Get integer value.
*/
public int getInteger(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException ex) {
throw new FtpException("BaseProperties.getInteger()", ex);
}
}
public int getInteger(final String str, final int intVal) {
try {
return getInteger(str);
} catch (FtpException ex) {
return intVal;
}
}
/**
* Get long value.
*/
public long getLong(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return Long.parseLong(value);
} catch (NumberFormatException ex) {
throw new FtpException("BaseProperties.getLong()", ex);
}
}
public long getLong(final String str, final long val) {
try {
return getLong(str);
} catch (FtpException ex) {
return val;
}
}
/**
* Get double value.
*/
public double getDouble(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException ex) {
throw new FtpException("BaseProperties.getDouble()", ex);
}
}
public double getDouble(final String str, final double doubleVal) {
try {
return getDouble(str);
} catch (FtpException ex) {
return doubleVal;
}
}
/**
* Get <code>InetAddress</code>.
*/
public InetAddress getInetAddress(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return InetAddress.getByName(value);
} catch (UnknownHostException ex) {
throw new FtpException("Host " + value + " not found");
}
}
public InetAddress getInetAddress(final String str, final InetAddress addr) {
try {
return getInetAddress(str);
} catch (FtpException ex) {
return addr;
}
}
/**
* Get <code>String</code>.
*/
public String getString(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
return value;
}
public String getString(final String str, final String s) {
try {
return getString(str);
} catch (FtpException ex) {
return s;
}
}
/**
* Get <code>File</code> object.
*/
public File getFile(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
return new File(value);
}
public File getFile(final String str, final File fl) {
try {
return getFile(str);
} catch (FtpException ex) {
return fl;
}
}
/**
* Get <code>Class</code> object
*/
public Class<?> getClass(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return Class.forName(value);
} catch (ClassNotFoundException ex) {
throw new FtpException("BaseProperties.getClass()", ex);
}
}
public Class<?> getClass(final String str, final Class<?> cls) {
try {
return getClass(str);
} catch (FtpException ex) {
return cls;
}
}
/**
* Get <code>TimeZone</code>
*/
public TimeZone getTimeZone(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
return TimeZone.getTimeZone(value);
}
public TimeZone getTimeZone(final String str, final TimeZone tz) {
try {
return getTimeZone(str);
} catch (FtpException ex) {
return tz;
}
}
/**
* Get <code>DateFormat</code> object.
*/
public SimpleDateFormat getDateFormat(final String str) throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return new SimpleDateFormat(value);
} catch (IllegalArgumentException e) {
throw new FtpException("Date format was incorrect: " + value, e);
}
}
public SimpleDateFormat getDateFormat(final String str,
final SimpleDateFormat fmt) {
try {
return getDateFormat(str);
} catch (FtpException ex) {
return fmt;
}
}
/**
* Get <code>Date</code> object.
*/
public Date getDate(final String str, final DateFormat fmt)
throws FtpException {
String value = getProperty(str);
if (value == null) {
throw new FtpException(str + " not found");
}
try {
return fmt.parse(value);
} catch (ParseException ex) {
throw new FtpException("BaseProperties.getdate()", ex);
}
}
public Date getDate(final String str, final DateFormat fmt, final Date dt) {
try {
return getDate(str, fmt);
} catch (FtpException ex) {
return dt;
}
}
// ////////////////////////////////////////
// ////// Properties Set Methods ////////
// ////////////////////////////////////////
/**
* Set boolean value.
*/
public void setProperty(final String key, final boolean val) {
setProperty(key, String.valueOf(val));
}
/**
* Set integer value.
*/
public void setProperty(final String key, final int val) {
setProperty(key, String.valueOf(val));
}
/**
* Set double value.
*/
public void setProperty(final String key, final double val) {
setProperty(key, String.valueOf(val));
}
/**
* Set float value.
*/
public void setProperty(final String key, final float val) {
setProperty(key, String.valueOf(val));
}
/**
* Set long value.
*/
public void setProperty(final String key, final long val) {
setProperty(key, String.valueOf(val));
}
/**
* Set <code>InetAddress</code>.
*/
public void setInetAddress(final String key, final InetAddress val) {
setProperty(key, val.getHostAddress());
}
/**
* Set <code>File</code> object.
*/
public void setProperty(final String key, final File val) {
setProperty(key, val.getAbsolutePath());
}
/**
* Set <code>DateFormat</code> object.
*/
public void setProperty(final String key, final SimpleDateFormat val) {
setProperty(key, val.toPattern());
}
/**
* Set <code>TimeZone</code> object.
*/
public void setProperty(final String key, final TimeZone val) {
setProperty(key, val.getID());
}
/**
* Set <code>Date</code> object.
*/
public void setProperty(final String key, final Date val,
final DateFormat fmt) {
setProperty(key, fmt.format(val));
}
/**
* Set <code>Class</code> object.
*/
public void setProperty(final String key, final Class<?> val) {
setProperty(key, val.getName());
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/BaseProperties.java | Java | art | 10,441 |
/*
* 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.util;
import java.io.File;
import java.io.FilenameFilter;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is regular expression filename filter.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class FileRegularFilter implements FilenameFilter {
private RegularExpr regularExpr = null;
/**
* Constructor.
*
* @param pattern
* regular expression
*/
public FileRegularFilter(String pattern) {
if ((pattern == null) || pattern.equals("") || pattern.equals("*")) {
regularExpr = null;
} else {
regularExpr = new RegularExpr(pattern);
}
}
/**
* Tests if a specified file should be included in a file list.
*
* @param dir
* - the directory in which the file was found
* @param name
* - the name of the file.
*/
public boolean accept(File dir, String name) {
if (regularExpr == null) {
return true;
}
return regularExpr.isMatch(name);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/FileRegularFilter.java | Java | art | 1,939 |
/*
* 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.util;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Thrown if the provided string representation does not match a valid IP port
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IllegalPortException extends IllegalArgumentException {
private static final long serialVersionUID = -7771719692741419931L;
public IllegalPortException() {
super();
}
public IllegalPortException(String s) {
super(s);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/IllegalPortException.java | Java | art | 1,336 |
/*
* 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.util;
import java.util.Locale;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Condition that tests the OS type.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public final class OS {
private static final String FAMILY_OS_400 = "os/400";
private static final String FAMILY_Z_OS = "z/os";
private static final String FAMILY_WIN9X = "win9x";
private static final String FAMILY_OPENVMS = "openvms";
private static final String FAMILY_UNIX = "unix";
private static final String FAMILY_TANDEM = "tandem";
private static final String FAMILY_MAC = "mac";
private static final String FAMILY_DOS = "dos";
private static final String FAMILY_NETWARE = "netware";
private static final String FAMILY_OS_2 = "os/2";
private static final String FAMILY_WINDOWS = "windows";
private static final String OS_NAME = System.getProperty("os.name")
.toLowerCase(Locale.US);
private static final String OS_ARCH = System.getProperty("os.arch")
.toLowerCase(Locale.US);
private static final String OS_VERSION = System.getProperty("os.version")
.toLowerCase(Locale.US);
private static final String PATH_SEP = System.getProperty("path.separator");
/**
* Default constructor
*/
private OS() {
}
/**
* Determines if the OS on which Ant is executing matches the given OS
* family. * Possible values:<br />
* <ul>
* <li>dos</li>
* <li>mac</li>
* <li>netware</li>
* <li>os/2</li>
* <li>tandem</li>
* <li>unix</li>
* <li>windows</li>
* <li>win9x</li>
* <li>z/os</li>
* <li>os/400</li>
* </ul>
*
* @param family
* the family to check for
* @return true if the OS matches
*/
private static boolean isFamily(final String family) {
return isOs(family, null, null, null);
}
public static boolean isFamilyDOS() {
return isFamily(FAMILY_DOS);
}
public static boolean isFamilyMac() {
return isFamily(FAMILY_MAC);
}
public static boolean isFamilyNetware() {
return isFamily(FAMILY_NETWARE);
}
public static boolean isFamilyOS2() {
return isFamily(FAMILY_OS_2);
}
public static boolean isFamilyTandem() {
return isFamily(FAMILY_TANDEM);
}
public static boolean isFamilyUnix() {
return isFamily(FAMILY_UNIX);
}
public static boolean isFamilyWindows() {
return isFamily(FAMILY_WINDOWS);
}
public static boolean isFamilyWin9x() {
return isFamily(FAMILY_WIN9X);
}
public static boolean isFamilyZOS() {
return isFamily(FAMILY_Z_OS);
}
public static boolean isFamilyOS400() {
return isFamily(FAMILY_OS_400);
}
public static boolean isFamilyOpenVms() {
return isFamily(FAMILY_OPENVMS);
}
/**
* Determines if the OS on which Ant is executing matches the given OS name.
*
* @param name
* the OS name to check for
* @return true if the OS matches
*/
public static boolean isName(final String name) {
return isOs(null, name, null, null);
}
/**
* Determines if the OS on which Ant is executing matches the given OS
* architecture.
*
* @param arch
* the OS architecture to check for
* @return true if the OS matches
*/
public static boolean isArch(final String arch) {
return isOs(null, null, arch, null);
}
/**
* Determines if the OS on which Ant is executing matches the given OS
* version.
*
* @param version
* the OS version to check for
* @return true if the OS matches
*/
public static boolean isVersion(final String version) {
return isOs(null, null, null, version);
}
/**
* Determines if the OS on which Ant is executing matches the given OS
* family, name, architecture and version
*
* @param family
* The OS family
* @param name
* The OS name
* @param arch
* The OS architecture
* @param version
* The OS version
* @return true if the OS matches
*/
public static boolean isOs(final String family, final String name,
final String arch, final String version) {
boolean retValue = false;
if (family != null || name != null || arch != null || version != null) {
boolean isFamily = true;
boolean isName = true;
boolean isArch = true;
boolean isVersion = true;
if (family != null) {
if (family.equals(FAMILY_WINDOWS)) {
isFamily = OS_NAME.indexOf(FAMILY_WINDOWS) > -1;
} else if (family.equals(FAMILY_OS_2)) {
isFamily = OS_NAME.indexOf(FAMILY_OS_2) > -1;
} else if (family.equals(FAMILY_NETWARE)) {
isFamily = OS_NAME.indexOf(FAMILY_NETWARE) > -1;
} else if (family.equals(FAMILY_DOS)) {
isFamily = PATH_SEP.equals(";")
&& !isFamily(FAMILY_NETWARE);
} else if (family.equals(FAMILY_MAC)) {
isFamily = OS_NAME.indexOf(FAMILY_MAC) > -1;
} else if (family.equals(FAMILY_TANDEM)) {
isFamily = OS_NAME.indexOf("nonstop_kernel") > -1;
} else if (family.equals(FAMILY_UNIX)) {
isFamily = PATH_SEP.equals(":")
&& !isFamily(FAMILY_OPENVMS)
&& (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x"));
} else if (family.equals(FAMILY_WIN9X)) {
isFamily = isFamily(FAMILY_WINDOWS)
&& (OS_NAME.indexOf("95") >= 0
|| OS_NAME.indexOf("98") >= 0
|| OS_NAME.indexOf("me") >= 0 || OS_NAME
.indexOf("ce") >= 0);
} else if (family.equals(FAMILY_Z_OS)) {
isFamily = OS_NAME.indexOf(FAMILY_Z_OS) > -1
|| OS_NAME.indexOf("os/390") > -1;
} else if (family.equals(FAMILY_OS_400)) {
isFamily = OS_NAME.indexOf(FAMILY_OS_400) > -1;
} else if (family.equals(FAMILY_OPENVMS)) {
isFamily = OS_NAME.indexOf(FAMILY_OPENVMS) > -1;
} else {
throw new IllegalArgumentException(
"Don\'t know how to detect os family \"" + family
+ "\"");
}
}
if (name != null) {
isName = name.equals(OS_NAME);
}
if (arch != null) {
isArch = arch.equals(OS_ARCH);
}
if (version != null) {
isVersion = version.equals(OS_VERSION);
}
retValue = isFamily && isName && isArch && isVersion;
}
return retValue;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/OS.java | Java | art | 8,063 |
/*
* 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.util;
/**
* <strong>Internal class, do not use directly.</strong>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class ClassUtils {
/**
* Checks if a class is a subclass of a class with the specified name. Used
* as an instanceOf without having to load the class, useful when trying to
* check for classes that might not be available in the runtime JRE.
*
* @param clazz
* The class to check
* @param className
* The class name to look for in the super classes
* @return true if the class extends a class by the specified name.
*/
public static boolean extendsClass(final Class<?> clazz, String className) {
Class<?> superClass = clazz.getSuperclass();
while (superClass != null) {
if (superClass.getName().equals(className)) {
return true;
}
superClass = superClass.getSuperclass();
}
return false;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/ClassUtils.java | Java | art | 1,852 |
/*
* 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.util;
import java.util.Map;
/**
* <strong>Internal class, do not use directly.</strong>
*
* String utility methods.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class StringUtils {
/**
* This is a string replacement method.
*/
public final static String replaceString(String source, String oldStr,
String newStr) {
StringBuffer sb = new StringBuffer(source.length());
int sind = 0;
int cind = 0;
while ((cind = source.indexOf(oldStr, sind)) != -1) {
sb.append(source.substring(sind, cind));
sb.append(newStr);
sind = cind + oldStr.length();
}
sb.append(source.substring(sind));
return sb.toString();
}
/**
* Replace string
*/
public final static String replaceString(String source, Object[] args) {
int startIndex = 0;
int openIndex = source.indexOf('{', startIndex);
if (openIndex == -1) {
return source;
}
int closeIndex = source.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
return source;
}
StringBuffer sb = new StringBuffer();
sb.append(source.substring(startIndex, openIndex));
while (true) {
String intStr = source.substring(openIndex + 1, closeIndex);
int index = Integer.parseInt(intStr);
sb.append(args[index]);
startIndex = closeIndex + 1;
openIndex = source.indexOf('{', startIndex);
if (openIndex == -1) {
sb.append(source.substring(startIndex));
break;
}
closeIndex = source.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
sb.append(source.substring(startIndex));
break;
}
sb.append(source.substring(startIndex, openIndex));
}
return sb.toString();
}
/**
* Replace string.
*/
public final static String replaceString(String source,
Map<String, Object> args) {
int startIndex = 0;
int openIndex = source.indexOf('{', startIndex);
if (openIndex == -1) {
return source;
}
int closeIndex = source.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
return source;
}
StringBuffer sb = new StringBuffer();
sb.append(source.substring(startIndex, openIndex));
while (true) {
String key = source.substring(openIndex + 1, closeIndex);
Object val = args.get(key);
if (val != null) {
sb.append(val);
}
startIndex = closeIndex + 1;
openIndex = source.indexOf('{', startIndex);
if (openIndex == -1) {
sb.append(source.substring(startIndex));
break;
}
closeIndex = source.indexOf('}', startIndex);
if ((closeIndex == -1) || (openIndex > closeIndex)) {
sb.append(source.substring(startIndex));
break;
}
sb.append(source.substring(startIndex, openIndex));
}
return sb.toString();
}
/**
* This method is used to insert HTML block dynamically
*
* @param source the HTML code to be processes
* @param bReplaceNl if true '\n' will be replaced by <br>
* @param bReplaceTag if true '<' will be replaced by < and
* '>' will be replaced by >
* @param bReplaceQuote if true '\"' will be replaced by "
*/
public final static String formatHtml(String source, boolean bReplaceNl,
boolean bReplaceTag, boolean bReplaceQuote) {
StringBuffer sb = new StringBuffer();
int len = source.length();
for (int i = 0; i < len; i++) {
char c = source.charAt(i);
switch (c) {
case '\"':
if (bReplaceQuote)
sb.append(""");
else
sb.append(c);
break;
case '<':
if (bReplaceTag)
sb.append("<");
else
sb.append(c);
break;
case '>':
if (bReplaceTag)
sb.append(">");
else
sb.append(c);
break;
case '\n':
if (bReplaceNl) {
if (bReplaceTag)
sb.append("<br>");
else
sb.append("<br>");
} else {
sb.append(c);
}
break;
case '\r':
break;
case '&':
sb.append("&");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* Pad string object
*/
public final static String pad(String src, char padChar, boolean rightPad,
int totalLength) {
int srcLength = src.length();
if (srcLength >= totalLength) {
return src;
}
int padLength = totalLength - srcLength;
StringBuffer sb = new StringBuffer(padLength);
for (int i = 0; i < padLength; ++i) {
sb.append(padChar);
}
if (rightPad) {
return src + sb.toString();
} else {
return sb.toString() + src;
}
}
/**
* Get hex string from byte array
*/
public final static String toHexString(byte[] res) {
StringBuffer sb = new StringBuffer(res.length << 1);
for (int i = 0; i < res.length; i++) {
String digit = Integer.toHexString(0xFF & res[i]);
if (digit.length() == 1) {
digit = '0' + digit;
}
sb.append(digit);
}
return sb.toString().toUpperCase();
}
/**
* Get byte array from hex string
*/
public final static byte[] toByteArray(String hexString) {
int arrLength = hexString.length() >> 1;
byte buff[] = new byte[arrLength];
for (int i = 0; i < arrLength; i++) {
int index = i << 1;
String digit = hexString.substring(index, index + 2);
buff[i] = (byte) Integer.parseInt(digit, 16);
}
return buff;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/StringUtils.java | Java | art | 7,566 |
/*
* 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.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Standard date related utility methods.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DateUtils {
private static final TimeZone TIME_ZONE_UTC = TimeZone.getTimeZone("UTC");
private final static String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
/*
* Creates the DateFormat object used to parse/format
* dates in FTP format.
*/
private static final ThreadLocal<DateFormat> FTP_DATE_FORMAT = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
DateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
df.setLenient(false);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
};
/**
* Get unix style date string.
*/
public final static String getUnixDate(long millis) {
if (millis < 0) {
return "------------";
}
StringBuffer sb = new StringBuffer(16);
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
// month
sb.append(MONTHS[cal.get(Calendar.MONTH)]);
sb.append(' ');
// day
int day = cal.get(Calendar.DATE);
if (day < 10) {
sb.append(' ');
}
sb.append(day);
sb.append(' ');
long sixMonth = 15811200000L; // 183L * 24L * 60L * 60L * 1000L;
long nowTime = System.currentTimeMillis();
if (Math.abs(nowTime - millis) > sixMonth) {
// year
int year = cal.get(Calendar.YEAR);
sb.append(' ');
sb.append(year);
} else {
// hour
int hh = cal.get(Calendar.HOUR_OF_DAY);
if (hh < 10) {
sb.append('0');
}
sb.append(hh);
sb.append(':');
// minute
int mm = cal.get(Calendar.MINUTE);
if (mm < 10) {
sb.append('0');
}
sb.append(mm);
}
return sb.toString();
}
/**
* Get ISO 8601 timestamp.
*/
public final static String getISO8601Date(long millis) {
StringBuffer sb = new StringBuffer(19);
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
// year
sb.append(cal.get(Calendar.YEAR));
// month
sb.append('-');
int month = cal.get(Calendar.MONTH) + 1;
if (month < 10) {
sb.append('0');
}
sb.append(month);
// date
sb.append('-');
int date = cal.get(Calendar.DATE);
if (date < 10) {
sb.append('0');
}
sb.append(date);
// hour
sb.append('T');
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour < 10) {
sb.append('0');
}
sb.append(hour);
// minute
sb.append(':');
int min = cal.get(Calendar.MINUTE);
if (min < 10) {
sb.append('0');
}
sb.append(min);
// second
sb.append(':');
int sec = cal.get(Calendar.SECOND);
if (sec < 10) {
sb.append('0');
}
sb.append(sec);
return sb.toString();
}
/**
* Get FTP date.
*/
public final static String getFtpDate(long millis) {
StringBuffer sb = new StringBuffer(20);
// MLST should use UTC
Calendar cal = new GregorianCalendar(TIME_ZONE_UTC);
cal.setTimeInMillis(millis);
// year
sb.append(cal.get(Calendar.YEAR));
// month
int month = cal.get(Calendar.MONTH) + 1;
if (month < 10) {
sb.append('0');
}
sb.append(month);
// date
int date = cal.get(Calendar.DATE);
if (date < 10) {
sb.append('0');
}
sb.append(date);
// hour
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour < 10) {
sb.append('0');
}
sb.append(hour);
// minute
int min = cal.get(Calendar.MINUTE);
if (min < 10) {
sb.append('0');
}
sb.append(min);
// second
int sec = cal.get(Calendar.SECOND);
if (sec < 10) {
sb.append('0');
}
sb.append(sec);
// millisecond
sb.append('.');
int milli = cal.get(Calendar.MILLISECOND);
if (milli < 100) {
sb.append('0');
}
if (milli < 10) {
sb.append('0');
}
sb.append(milli);
return sb.toString();
}
/*
* Parses a date in the format used by the FTP commands
* involving dates(MFMT, MDTM)
*/
public final static Date parseFTPDate(String dateStr) throws ParseException{
return FTP_DATE_FORMAT.get().parse(dateStr);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/DateUtils.java | Java | art | 6,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.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Random;
/**
* <strong>Internal class, do not use directly.</strong>
*
* IO utility methods.
*
* <b>Note: Why not use commons-io?</b>
* While many of these utility methods are also provided by the Apache
* commons-io library we prefer to our own implementation to, using a external
* library might cause additional constraints on users embedding FtpServer.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IoUtils {
/**
* Random number generator to make unique file name
*/
private final static Random RANDOM_GEN = new Random(System
.currentTimeMillis());
/**
* Get a <code>BufferedInputStream</code>.
*/
public final static BufferedInputStream getBufferedInputStream(
InputStream in) {
BufferedInputStream bin = null;
if (in instanceof java.io.BufferedInputStream) {
bin = (BufferedInputStream) in;
} else {
bin = new BufferedInputStream(in);
}
return bin;
}
/**
* Get a <code>BufferedOutputStream</code>.
*/
public final static BufferedOutputStream getBufferedOutputStream(
OutputStream out) {
BufferedOutputStream bout = null;
if (out instanceof java.io.BufferedOutputStream) {
bout = (BufferedOutputStream) out;
} else {
bout = new BufferedOutputStream(out);
}
return bout;
}
/**
* Get <code>BufferedReader</code>.
*/
public final static BufferedReader getBufferedReader(Reader reader) {
BufferedReader buffered = null;
if (reader instanceof java.io.BufferedReader) {
buffered = (BufferedReader) reader;
} else {
buffered = new BufferedReader(reader);
}
return buffered;
}
/**
* Get <code>BufferedWriter</code>.
*/
public final static BufferedWriter getBufferedWriter(Writer wr) {
BufferedWriter bw = null;
if (wr instanceof java.io.BufferedWriter) {
bw = (BufferedWriter) wr;
} else {
bw = new BufferedWriter(wr);
}
return bw;
}
/**
* Get unique file object.
*/
public final static File getUniqueFile(File oldFile) {
File newFile = oldFile;
while (true) {
if (!newFile.exists()) {
break;
}
newFile = new File(oldFile.getAbsolutePath() + '.'
+ Math.abs(RANDOM_GEN.nextLong()));
}
return newFile;
}
/**
* No exception <code>InputStream</code> close method.
*/
public final static void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (Exception ex) {
}
}
}
/**
* No exception <code>OutputStream</code> close method.
*/
public final static void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (Exception ex) {
}
}
}
/**
* No exception <code>java.io.Reader</code> close method.
*/
public final static void close(Reader rd) {
if (rd != null) {
try {
rd.close();
} catch (Exception ex) {
}
}
}
/**
* No exception <code>java.io.Writer</code> close method.
*/
public final static void close(Writer wr) {
if (wr != null) {
try {
wr.close();
} catch (Exception ex) {
}
}
}
/**
* Get exception stack trace.
*/
public final static String getStackTrace(Throwable ex) {
String result = "";
if (ex != null) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.close();
sw.close();
result = sw.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* Copy chars from a <code>Reader</code> to a <code>Writer</code>.
*
* @param bufferSize
* Size of internal buffer to use.
*/
public final static void copy(Reader input, Writer output, int bufferSize)
throws IOException {
char buffer[] = new char[bufferSize];
int n = 0;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
}
/**
* Copy chars from a <code>InputStream</code> to a <code>OutputStream</code>
* .
*
* @param bufferSize
* Size of internal buffer to use.
*/
public final static void copy(InputStream input, OutputStream output,
int bufferSize) throws IOException {
byte buffer[] = new byte[bufferSize];
int n = 0;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
}
/**
* Read fully from reader
*/
public final static String readFully(Reader reader) throws IOException {
StringWriter writer = new StringWriter();
copy(reader, writer, 1024);
return writer.toString();
}
/**
* Read fully from stream
*/
public final static String readFully(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
InputStreamReader reader = new InputStreamReader(input);
copy(reader, writer, 1024);
return writer.toString();
}
public final static void delete(File file) throws IOException {
if (!file.exists()) {
return;
} else if (file.isDirectory()) {
deleteDir(file);
} else {
deleteFile(file);
}
}
private final static void deleteDir(File dir) throws IOException {
File[] children = dir.listFiles();
if (children == null) {
return;
}
for (int i = 0; i < children.length; i++) {
File file = children[i];
delete(file);
}
if (!dir.delete()) {
throw new IOException("Failed to delete directory: " + dir);
}
}
private final static void deleteFile(File file) throws IOException {
if (!file.delete()) {
// hack around bug where files will sometimes not be deleted on
// Windows
if (OS.isFamilyWindows()) {
System.gc();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
if (!file.delete()) {
throw new IOException("Failed to delete file: " + file);
}
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/IoUtils.java | Java | art | 8,162 |
/*
* 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.util;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Encodes and decodes socket addresses (IP and port) from and to the format
* used with for example the PORT and PASV command
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SocketAddressEncoder {
private static int convertAndValidateNumber(String s) {
int i = Integer.parseInt(s);
if (i < 0) {
throw new IllegalArgumentException("Token can not be less than 0");
} else if (i > 255) {
throw new IllegalArgumentException(
"Token can not be larger than 255");
}
return i;
}
public static InetSocketAddress decode(String str)
throws UnknownHostException {
StringTokenizer st = new StringTokenizer(str, ",");
if (st.countTokens() != 6) {
throw new IllegalInetAddressException("Illegal amount of tokens");
}
StringBuffer sb = new StringBuffer();
try {
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append('.');
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append('.');
sb.append(convertAndValidateNumber(st.nextToken()));
sb.append('.');
sb.append(convertAndValidateNumber(st.nextToken()));
} catch (IllegalArgumentException e) {
throw new IllegalInetAddressException(e.getMessage());
}
InetAddress dataAddr = InetAddress.getByName(sb.toString());
// get data server port
int dataPort = 0;
try {
int hi = convertAndValidateNumber(st.nextToken());
int lo = convertAndValidateNumber(st.nextToken());
dataPort = (hi << 8) | lo;
} catch (IllegalArgumentException ex) {
throw new IllegalPortException("Invalid data port: " + str);
}
return new InetSocketAddress(dataAddr, dataPort);
}
public static String encode(InetSocketAddress address) {
InetAddress servAddr = address.getAddress();
int servPort = address.getPort();
return servAddr.getHostAddress().replace('.', ',') + ','
+ (servPort >> 8) + ',' + (servPort & 0xFF);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/SocketAddressEncoder.java | Java | art | 3,263 |
/*
* 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.util;
/**
* <strong>Internal class, do not use directly.</strong>
*
* Thrown if the provided string representation does not match a valid IP
* address
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IllegalInetAddressException extends IllegalArgumentException {
private static final long serialVersionUID = -7771719692741419933L;
public IllegalInetAddressException() {
super();
}
public IllegalInetAddressException(String s) {
super(s);
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/IllegalInetAddressException.java | Java | art | 1,363 |
/*
* 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.util;
/**
* <strong>Internal class, do not use directly.</strong>
*
* This is a simplified regular character mattching class. Supports *?^[]-
* pattern characters.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class RegularExpr {
private char[] pattern;
/**
* Constructor.
*
* @param pattern
* regular expression
*/
public RegularExpr(String pattern) {
this.pattern = pattern.toCharArray();
}
/**
* Compare string with a regular expression.
*/
public boolean isMatch(String name) {
// common pattern - *
if ((pattern.length == 1) && (pattern[0] == '*')) {
return true;
}
return isMatch(name.toCharArray(), 0, 0);
}
/**
* Is a match?
*/
private boolean isMatch(char[] strName, int strIndex, int patternIndex) {
while (true) {
// no more pattern characters
// if no more strName characters - return true
if (patternIndex >= pattern.length) {
return strIndex == strName.length;
}
char pc = pattern[patternIndex++];
switch (pc) {
// Match a single character in the range
// If no more strName character - return false
case '[':
// no more string character - returns false
// example : pattern = ab[^c] and string = ab
if (strIndex >= strName.length) {
return false;
}
char fc = strName[strIndex++];
char lastc = 0;
boolean bMatch = false;
boolean bNegete = false;
boolean bFirst = true;
while (true) {
// single character match
// no more pattern character - error condition.
if (patternIndex >= pattern.length) {
return false;
}
pc = pattern[patternIndex++];
// end character - break out the loop
// if end bracket is the first character - always a match.
// example pattern - [], [^]
if (pc == ']') {
if (bFirst) {
bMatch = true;
}
break;
}
// if already matched - just read the rest till we get ']'.
if (bMatch) {
continue;
}
// if the first character is the negete
// character - inverse the matching condition
if ((pc == '^') && bFirst) {
bNegete = true;
continue;
}
bFirst = false;
// '-' range check
if (pc == '-') {
// pattern string is [a- error condition.
if (patternIndex >= pattern.length) {
return false;
}
// read the high range character and compare.
pc = pattern[patternIndex++];
bMatch = (fc >= lastc) && (fc <= pc);
lastc = pc;
}
// Single character match check. It might also be the
// low range character.
else {
lastc = pc;
bMatch = (pc == fc);
}
}
// no match - return false.
if (bNegete) {
if (bMatch) {
return false;
}
} else {
if (!bMatch) {
return false;
}
}
break;
// * - skip zero or more characters
// No more pattern character - return true
// Increment strIndex till the rest of the pattern matches.
case '*':
// no more string character remaining - returns true
if (patternIndex >= pattern.length) {
return true;
}
// compare rest of the string
do {
if (isMatch(strName, strIndex++, patternIndex)) {
return true;
}
} while (strIndex < strName.length);
// Example pattern is (a*b) and the string is (adfdc).
return false;
// ? - skip one character - increment strIndex.
// If no more strName character - return false.
case '?':
// already at the end - no more character - returns false
if (strIndex >= strName.length) {
return false;
}
strIndex++;
break;
// match character.
default:
// already at the end - no match
if (strIndex >= strName.length) {
return false;
}
// the characters are not equal - no match
if (strName[strIndex++] != pc) {
return false;
}
break;
}
}
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/RegularExpr.java | Java | art | 6,437 |
/*
* 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.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* <strong>Internal class, do not use directly.</strong>
*
* String encryption utility methods.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class EncryptUtils {
/**
* Encrypt byte array.
*/
public final static byte[] encrypt(byte[] source, String algorithm)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.reset();
md.update(source);
return md.digest();
}
/**
* Encrypt string
*/
public final static String encrypt(String source, String algorithm)
throws NoSuchAlgorithmException {
byte[] resByteArray = encrypt(source.getBytes(), algorithm);
return StringUtils.toHexString(resByteArray);
}
/**
* Encrypt string using MD5 algorithm
*/
public final static String encryptMD5(String source) {
if (source == null) {
source = "";
}
String result = "";
try {
result = encrypt(source, "MD5");
} catch (NoSuchAlgorithmException ex) {
// this should never happen
throw new RuntimeException(ex);
}
return result;
}
/**
* Encrypt string using SHA algorithm
*/
public final static String encryptSHA(String source) {
if (source == null) {
source = "";
}
String result = "";
try {
result = encrypt(source, "SHA");
} catch (NoSuchAlgorithmException ex) {
// this should never happen
throw new RuntimeException(ex);
}
return result;
}
}
| zzh-simple-hr | Zftp/core/main/java/org/apache/ftpserver/util/EncryptUtils.java | Java | art | 2,615 |
/*
* 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.examples;
import java.io.File;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.ssl.SslConfigurationFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class EmbeddingFtpServer {
public static void main(String[] args) throws Exception {
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory = new ListenerFactory();
// set the port of the listener
factory.setPort(2221);
// define SSL configuration
SslConfigurationFactory ssl = new SslConfigurationFactory();
ssl.setKeystoreFile(new File("src/test/resources/ftpserver.jks"));
ssl.setKeystorePassword("password");
// set the SSL configuration for the listener
factory.setSslConfiguration(ssl.createSslConfiguration());
factory.setImplicitSsl(true);
// replace the default listener
serverFactory.addListener("default", factory.createListener());
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("myusers.properties"));
serverFactory.setUserManager(userManagerFactory.createUserManager());
// start the server
FtpServer server = serverFactory.createServer();
server.start();
}
}
| zzh-simple-hr | Zftp/core/examples/java/org/apache/ftpserver/examples/EmbeddingFtpServer.java | Java | art | 2,413 |
package org.apache.ftpserver.examples;
/*
* 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.
*/
import java.io.File;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.UserFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class ManagingUsers {
public static void main(String[] args) throws Exception {
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("myusers.properties"));
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
UserManager um = userManagerFactory.createUserManager();
UserFactory userFact = new UserFactory();
userFact.setName("myNewUser");
userFact.setPassword("secret");
userFact.setHomeDirectory("ftproot");
User user = userFact.createUser();
um.save(user);
}
}
| zzh-simple-hr | Zftp/core/examples/java/org/apache/ftpserver/examples/ManagingUsers.java | Java | art | 1,935 |
/*
* 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.io.IOException;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class MockFtplet extends DefaultFtplet {
protected static MockFtpletCallback callback = new MockFtpletCallback();
public FtpletContext context;
public boolean destroyed = false;
public void destroy() {
destroyed = true;
callback.destroy();
}
public void init(FtpletContext ftpletContext) throws FtpException {
this.context = ftpletContext;
callback.init(ftpletContext);
}
public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onAppendEnd(session, request);
}
public FtpletResult onAppendStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onAppendStart(session, request);
}
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
return callback.onConnect(session);
}
public FtpletResult onDeleteEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onDeleteEnd(session, request);
}
public FtpletResult onDeleteStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onDeleteStart(session, request);
}
public FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException {
return callback.onDisconnect(session);
}
public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onDownloadEnd(session, request);
}
public FtpletResult onDownloadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onDownloadStart(session, request);
}
public FtpletResult onLogin(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onLogin(session, request);
}
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onMkdirEnd(session, request);
}
public FtpletResult onMkdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onMkdirStart(session, request);
}
public FtpletResult onRenameEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onRenameEnd(session, request);
}
public FtpletResult onRenameStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onRenameStart(session, request);
}
public FtpletResult onRmdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onRmdirEnd(session, request);
}
public FtpletResult onRmdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onRmdirStart(session, request);
}
public FtpletResult onSite(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onSite(session, request);
}
public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onUploadEnd(session, request);
}
public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onUploadStart(session, request);
}
public FtpletResult onUploadUniqueEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onUploadUniqueEnd(session, request);
}
public FtpletResult onUploadUniqueStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return callback.onUploadUniqueStart(session, request);
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ftpletcontainer/MockFtplet.java | Java | art | 5,399 |
/*
* 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.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.apache.ftpserver.ftplet.DefaultFtpReply;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpStatistics;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.DefaultFtpRequest;
import org.apache.ftpserver.impl.DefaultFtpSession;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class FtpLetContainerTestTemplate extends TestCase {
private final List<String> calls = new ArrayList<String>();
protected void setUp() throws Exception {
MockFtplet.callback = new MockFtpletCallback();
MockFtpletCallback.returnValue = FtpletResult.DEFAULT;
}
protected abstract FtpletContainer createFtpletContainer(Map<String, Ftplet> ftplets);
private static class MockFtpletContext implements FtpletContext {
public FileSystemFactory getFileSystemManager() {
return null;
}
public FtpStatistics getFtpStatistics() {
return null;
}
public Ftplet getFtplet(String name) {
return null;
}
public UserManager getUserManager() {
return null;
}
}
public void testAddAndGetFtplet() throws FtpException {
MockFtplet ftplet1 = new MockFtplet();
MockFtplet ftplet2 = new MockFtplet();
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
assertSame(ftplet1, container.getFtplet("ftplet1"));
assertSame(ftplet2, container.getFtplet("ftplet2"));
}
public void testFtpletLifecyclePreContainerInit() throws FtpException {
MockFtplet ftplet = new MockFtplet();
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet);
FtpletContainer container = createFtpletContainer(ftplets);
// ftplet should be initialized before the container is
assertNull(ftplet.context);
container.init(new MockFtpletContext());
assertNotNull(ftplet.context);
// make sure ftplets get's destroyed
assertFalse(ftplet.destroyed);
container.destroy();
assertTrue(ftplet.destroyed);
}
public void testOnConnect() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onConnect(session);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onConnect(session);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.onConnect(new DefaultFtpSession(null));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnDisconnect() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onDisconnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onDisconnect(session);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onDisconnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onDisconnect(session);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.onDisconnect(new DefaultFtpSession(null));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnLogin() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onLogin(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onLogin(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onLogin(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onLogin(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"PASS"), null);
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnDeleteStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onDeleteStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onDeleteStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onDeleteStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onDeleteStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"DELE"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnDeleteEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onDeleteEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onDeleteEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onDeleteEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onDeleteEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"DELE"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnUploadStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onUploadStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onUploadStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onUploadStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onUploadStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"STOR"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnUploadEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onUploadEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onUploadEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"STOR"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnDownloadStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onDownloadStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onDownloadStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onDownloadStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onDownloadStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RETR"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnDownloadEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onDownloadEnd(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onDownloadEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onDownloadEnd(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onDownloadEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RETR"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnRmdirStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onRmdirStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onRmdirStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onRmdirStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onRmdirStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RMD"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnRmdirEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onRmdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onRmdirEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onRmdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onRmdirEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RMD"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnMkdirStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onMkdirStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onMkdirStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onMkdirStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onMkdirStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"MKD"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnMkdirEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onMkdirEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onMkdirEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"MKD"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnAppendStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onAppendStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onAppendStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onAppendStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onAppendStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"APPE"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnAppendEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onAppendEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onAppendEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"APPE"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnUploadUniqueStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onUploadUniqueStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onUploadUniqueStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onUploadUniqueStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onUploadUniqueStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"STOU"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnUploadUniqueEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onUploadUniqueEnd(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onUploadUniqueEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onUploadUniqueEnd(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onUploadUniqueEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"STOU"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnRenameStart() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onRenameStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet1");
return super.onRenameStart(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onRenameStart(FtpSession session,
FtpRequest request) throws FtpException, IOException {
calls.add("ftplet2");
return super.onRenameStart(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RNTO"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnRenameEnd() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onRenameEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onRenameEnd(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onRenameEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onRenameEnd(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.afterCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"RNTO"), new DefaultFtpReply(200, "foo"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
public void testOnSite() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onSite(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onSite(session, request);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onSite(FtpSession session, FtpRequest request)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onSite(session, request);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.beforeCommand(new DefaultFtpSession(null), new DefaultFtpRequest(
"SITE"));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
/**
* First test checking the call order of Ftplets
*/
public void testFtpletCallOrder1() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onConnect(session);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onConnect(session);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet1", ftplet1);
ftplets.put("ftplet2", ftplet2);
FtpletContainer container = createFtpletContainer(ftplets);
container.onConnect(new DefaultFtpSession(null));
assertEquals(2, calls.size());
assertEquals("ftplet1", calls.get(0));
assertEquals("ftplet2", calls.get(1));
}
/**
* First test checking the call order of Ftplets
*/
public void testFtpletCallOrder2() throws FtpException, IOException {
MockFtplet ftplet1 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet1");
return super.onConnect(session);
}
};
MockFtplet ftplet2 = new MockFtplet() {
public FtpletResult onConnect(FtpSession session)
throws FtpException, IOException {
calls.add("ftplet2");
return super.onConnect(session);
}
};
Map<String, Ftplet> ftplets = new LinkedHashMap<String, Ftplet>();
ftplets.put("ftplet2", ftplet2);
ftplets.put("ftplet1", ftplet1);
FtpletContainer container = createFtpletContainer(ftplets);
container.onConnect(new DefaultFtpSession(null));
assertEquals(2, calls.size());
assertEquals("ftplet2", calls.get(0));
assertEquals("ftplet1", calls.get(1));
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ftpletcontainer/FtpLetContainerTestTemplate.java | Java | art | 29,481 |
/*
* 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.io.IOException;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletContext;
import org.apache.ftpserver.ftplet.FtpletResult;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class MockFtpletCallback extends DefaultFtplet {
public static FtpletResult returnValue;
public void destroy() {
}
public void init(FtpletContext ftpletContext) throws FtpException {
}
public FtpletResult onAppendEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onAppendStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
return returnValue;
}
public FtpletResult onDeleteEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onDeleteStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onDisconnect(FtpSession session) throws FtpException,
IOException {
return returnValue;
}
public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onDownloadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onLogin(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onMkdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onMkdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onRenameEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onRenameStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onRmdirEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onRmdirStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onSite(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onUploadStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onUploadUniqueEnd(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
public FtpletResult onUploadUniqueStart(FtpSession session, FtpRequest request)
throws FtpException, IOException {
return returnValue;
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ftpletcontainer/MockFtpletCallback.java | Java | art | 4,610 |
/*
* 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.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.listener.Listener;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.apache.mina.filter.firewall.Subnet;
/**
* Used for testing creation of custom listeners from Spring config
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a> *
*/
public class MyCustomListener implements Listener {
private int port;
public void setPort(int port) {
this.port = port;
}
public Set<FtpIoSession> getActiveSessions() {
return null;
}
public DataConnectionConfiguration getDataConnectionConfiguration() {
return null;
}
public int getIdleTimeout() {
return 0;
}
public int getPort() {
return port;
}
public String getServerAddress() {
return null;
}
public SslConfiguration getSslConfiguration() {
return null;
}
public boolean isImplicitSsl() {
return false;
}
public boolean isStopped() {
return false;
}
public boolean isSuspended() {
return false;
}
public void resume() {
}
public void start(FtpServerContext serverContext) {
}
public void stop() {
}
public void suspend() {
}
public List<InetAddress> getBlockedAddresses() {
return null;
}
public List<Subnet> getBlockedSubnets() {
return null;
}
public IpFilter getIpFilter() {
return null;
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/config/spring/MyCustomListener.java | Java | art | 2,727 |
/*
* 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 junit.framework.TestCase;
import org.apache.ftpserver.FtpServer;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ByteArrayResource;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class SpringConfigTestTemplate extends TestCase {
protected FtpServer createServer(String config) {
String completeConfig = "<server id=\"server\" xmlns=\"http://mina.apache.org/ftpserver/spring/v1\" "
+ "xmlns:beans=\"http://www.springframework.org/schema/beans\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\" "
+ "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd "
+ "http://mina.apache.org/ftpserver/spring/v1 http://mina.apache.org/ftpserver/ftpserver-1.0.xsd "
+ "\">"
+ config
+ "</server>";
XmlBeanFactory factory = new XmlBeanFactory(
new ByteArrayResource(completeConfig.getBytes()));
return (FtpServer) factory.getBean("server");
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/config/spring/SpringConfigTestTemplate.java | Java | art | 2,038 |
/*
* 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.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public class MockUserManager implements UserManager {
public User authenticate(Authentication authentication)
throws AuthenticationFailedException {
return null;
}
public void delete(String username) throws FtpException {
}
public boolean doesExist(String username) throws FtpException {
return false;
}
public String getAdminName() throws FtpException {
return null;
}
public String[] getAllUserNames() throws FtpException {
return null;
}
public User getUserByName(String username) throws FtpException {
return null;
}
public boolean isAdmin(String username) throws FtpException {
return false;
}
public void save(User user) throws FtpException {
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/config/spring/MockUserManager.java | Java | art | 1,970 |
/*
* 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 junit.framework.TestCase;
import org.apache.ftpserver.usermanager.impl.BaseUser;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class FileSystemViewTemplate extends TestCase {
protected static final String DIR1_NAME = "dir1";
protected BaseUser user = new BaseUser();
public void testChangeDirectory() throws Exception {
NativeFileSystemView view = new NativeFileSystemView(user);
assertEquals("/", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory(DIR1_NAME));
assertEquals("/" + DIR1_NAME, view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory("."));
assertEquals("/" + DIR1_NAME, view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory(".."));
assertEquals("/", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory("./" + DIR1_NAME));
assertEquals("/" + DIR1_NAME, view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory("~"));
assertEquals("/", view.getWorkingDirectory().getAbsolutePath());
}
public void testChangeDirectoryCaseInsensitive() throws Exception {
NativeFileSystemView view = new NativeFileSystemView(user, true);
assertEquals("/", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.changeWorkingDirectory("/DIR1"));
assertEquals("/dir1", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.getWorkingDirectory().doesExist());
assertTrue(view.changeWorkingDirectory("/dir1"));
assertEquals("/dir1", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.getWorkingDirectory().doesExist());
assertTrue(view.changeWorkingDirectory("/DiR1"));
assertEquals("/dir1", view.getWorkingDirectory().getAbsolutePath());
assertTrue(view.getWorkingDirectory().doesExist());
}
} | zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/filesystem/nativefs/impl/FileSystemViewTemplate.java | Java | art | 2,914 |
/*
* 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.util.List;
import junit.framework.TestCase;
import org.apache.ftpserver.ftplet.AuthorizationRequest;
import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.usermanager.impl.BaseUser;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class FtpFileTestTemplate extends TestCase {
protected static final String FILE2_PATH = "/dir1/file2";
protected static final String DIR1_PATH = "/dir1";
protected static final String DIR1_WITH_SLASH_PATH = "/dir1/";
protected static final String FILE1_PATH = "/file1";
protected static final String FILE3_PATH = "/file3";
protected static final User USER = new BaseUser() {
private static final long serialVersionUID = 4906315989316879758L;
public AuthorizationRequest authorize(AuthorizationRequest request) {
return request;
}
};
protected abstract FtpFile createFileObject(String fileName, User user);
public void testNullFileName() {
try {
createFileObject(null, USER);
fail("Must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK
}
}
public void testWhiteSpaceFileName() {
try {
createFileObject(" \t", USER);
fail("Must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK
}
}
public void testEmptyFileName() {
try {
createFileObject("", USER);
fail("Must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK
}
}
public void testNonLeadingSlash() {
try {
createFileObject("foo", USER);
fail("Must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK
}
}
public void testFullName() {
FtpFile fileObject = createFileObject(FILE2_PATH, USER);
assertEquals("/dir1/file2", fileObject.getAbsolutePath());
fileObject = createFileObject("/dir1/", USER);
assertEquals("/dir1", fileObject.getAbsolutePath());
fileObject = createFileObject("/dir1", USER);
assertEquals("/dir1", fileObject.getAbsolutePath());
}
public void testShortName() {
FtpFile fileObject = createFileObject("/dir1/file2", USER);
assertEquals("file2", fileObject.getName());
fileObject = createFileObject("/dir1/", USER);
assertEquals("dir1", fileObject.getName());
fileObject = createFileObject("/dir1", USER);
assertEquals("dir1", fileObject.getName());
}
public void testListFilesInOrder() {
FtpFile root = createFileObject("/", USER);
List<FtpFile> files = root.listFiles();
assertEquals(3, files.size());
assertEquals("dir1", files.get(0).getName());
assertEquals("file1", files.get(1).getName());
assertEquals("file3", files.get(2).getName());
}
} | zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/filesystem/nativefs/impl/FtpFileTestTemplate.java | Java | art | 3,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.clienttests;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.commons.net.ProtocolCommandEvent;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.ftpserver.ConnectionConfigFactory;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.impl.DefaultFtpServer;
import org.apache.ftpserver.impl.FtpIoSession;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.test.TestUtil;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.util.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class ClientTestTemplate extends TestCase {
private final Logger LOG = LoggerFactory
.getLogger(ClientTestTemplate.class);
protected static final String ADMIN_PASSWORD = "admin";
protected static final String ADMIN_USERNAME = "admin";
protected static final String ANONYMOUS_PASSWORD = "foo@bar.com";
protected static final String ANONYMOUS_USERNAME = "anonymous";
protected static final String TESTUSER2_USERNAME = "testuser2";
protected static final String TESTUSER1_USERNAME = "testuser1";
protected static final String TESTUSER_PASSWORD = "password";
protected DefaultFtpServer server;
protected FTPClient client;
private static final File USERS_FILE = new File(TestUtil.getBaseDir(),
"src/test/resources/users.properties");
private static final File TEST_TMP_DIR = new File("test-tmp");
protected static final File ROOT_DIR = new File(TEST_TMP_DIR, "ftproot");
protected FtpServerFactory createServer() throws Exception {
assertTrue(USERS_FILE.getAbsolutePath() + " must exist", USERS_FILE
.exists());
FtpServerFactory serverFactory = new FtpServerFactory();
serverFactory.setConnectionConfig(createConnectionConfigFactory()
.createConnectionConfig());
ListenerFactory listenerFactory = new ListenerFactory();
listenerFactory.setPort(0);
listenerFactory
.setDataConnectionConfiguration(createDataConnectionConfigurationFactory()
.createDataConnectionConfiguration());
serverFactory.addListener("default", listenerFactory.createListener());
PropertiesUserManagerFactory umFactory = new PropertiesUserManagerFactory();
umFactory.setAdminName("admin");
umFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
umFactory.setFile(USERS_FILE);
serverFactory.setUserManager(umFactory.createUserManager());
return serverFactory;
}
protected ConnectionConfigFactory createConnectionConfigFactory() {
return new ConnectionConfigFactory();
}
protected DataConnectionConfigurationFactory createDataConnectionConfigurationFactory() {
return new DataConnectionConfigurationFactory();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
initDirs();
initServer();
connectClient();
}
/**
* @throws IOException
*/
protected void initDirs() throws IOException {
cleanTmpDirs();
TEST_TMP_DIR.mkdirs();
ROOT_DIR.mkdirs();
}
/**
* @throws IOException
* @throws Exception
*/
protected void initServer() throws IOException, Exception {
// cast to internal class to get access to getters
server = (DefaultFtpServer) createServer().createServer();
if (isStartServer()) {
server.start();
}
}
protected int getListenerPort() {
return server.getListener("default").getPort();
}
protected boolean isStartServer() {
return true;
}
protected FTPClient createFTPClient() throws Exception {
FTPClient client = new FTPClient();
client.setDefaultTimeout(10000);
return client;
}
/**
* @throws Exception
*/
protected void connectClient() throws Exception {
client = createFTPClient();
client.addProtocolCommandListener(new ProtocolCommandListener() {
public void protocolCommandSent(ProtocolCommandEvent event) {
LOG.debug("> " + event.getMessage().trim());
}
public void protocolReplyReceived(ProtocolCommandEvent event) {
LOG.debug("< " + event.getMessage().trim());
}
});
if (isConnectClient()) {
doConnect();
}
}
protected void doConnect() throws Exception {
try {
client.connect("localhost", getListenerPort());
} catch (FTPConnectionClosedException e) {
// try again
Thread.sleep(200);
client.connect("localhost", getListenerPort());
}
}
protected boolean isConnectClient() {
return true;
}
protected void cleanTmpDirs() throws IOException {
if (TEST_TMP_DIR.exists()) {
IoUtils.delete(TEST_TMP_DIR);
}
}
protected FtpIoSession getActiveSession() {
return server.getListener("default").getActiveSessions().iterator()
.next();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
if (isConnectClient()) {
try {
client.quit();
} catch (Exception e) {
// ignore
}
}
if (server != null) {
server.stop();
}
cleanTmpDirs();
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/clienttests/ClientTestTemplate.java | Java | art | 6,915 |
/*
* 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.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.clienttests.ClientTestTemplate;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.test.TestUtil;
import org.apache.ftpserver.util.IoUtils;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class SSLTestTemplate extends ClientTestTemplate {
protected static final File FTPCLIENT_KEYSTORE = new File(TestUtil
.getBaseDir(), "src/test/resources/client.jks");
protected static final String KEYSTORE_PASSWORD = "password";
private static final File FTPSERVER_KEYSTORE = new File(TestUtil
.getBaseDir(), "src/test/resources/ftpserver.jks");
protected KeyManager clientKeyManager;
protected TrustManager clientTrustManager;
protected SslConfigurationFactory createSslConfiguration() {
SslConfigurationFactory sslConfigFactory = new SslConfigurationFactory();
sslConfigFactory.setKeystoreFile(FTPSERVER_KEYSTORE);
sslConfigFactory.setKeystorePassword(KEYSTORE_PASSWORD);
sslConfigFactory.setSslProtocol(getAuthValue());
sslConfigFactory.setClientAuthentication(getClientAuth());
sslConfigFactory.setKeyPassword(KEYSTORE_PASSWORD);
return sslConfigFactory;
}
protected FtpServerFactory createServer() throws Exception {
assertTrue(FTPSERVER_KEYSTORE.exists());
FtpServerFactory server = super.createServer();
ListenerFactory factory = new ListenerFactory(server.getListener("default"));
factory.setImplicitSsl(useImplicit());
factory.setSslConfiguration(createSslConfiguration().createSslConfiguration());
server.addListener("default", factory.createListener());
return server;
}
protected boolean useImplicit() {
return false;
}
protected String getClientAuth() {
return "false";
}
protected FTPSClient createFTPClient() throws Exception {
FTPSClient ftpsClient = new FTPSClient(useImplicit());
FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE);
KeyStore store = KeyStore.getInstance("jks");
store.load(fin, KEYSTORE_PASSWORD.toCharArray());
fin.close();
// initialize key manager factory
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray());
// initialize trust manager factory
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(store);
clientKeyManager = keyManagerFactory.getKeyManagers()[0];
clientTrustManager = trustManagerFactory.getTrustManagers()[0];
ftpsClient.setKeyManager(clientKeyManager);
ftpsClient.setTrustManager(clientTrustManager);
String auth = getAuthValue();
if (auth != null) {
ftpsClient.setAuthValue(auth);
if(auth.equals("SSL")) {
ftpsClient.setEnabledProtocols(new String[]{"SSLv3"});
}
}
return ftpsClient;
}
protected abstract String getAuthValue();
protected void writeDataToFile(File file, byte[] data) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data);
} finally {
IoUtils.close(fos);
}
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ssl/SSLTestTemplate.java | Java | art | 4,850 |
/*
* 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.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.ftpserver.util.IoUtils;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class ExplicitSecurityTestTemplate extends SSLTestTemplate {
protected static final File TEST_FILE1 = new File(ROOT_DIR, "test1.txt");
protected static final File TEST_FILE2 = new File(ROOT_DIR, "test2.txt");
protected static final byte[] TEST_DATA = "TESTDATA".getBytes();
protected void setUp() throws Exception {
super.setUp();
client.login(ADMIN_USERNAME, ADMIN_PASSWORD);
}
/**
* Tests that we can send command over the command channel. This is, in fact
* already tested by login in setup but an explicit test is good anyways.
*/
public void testCommandChannel() throws Exception {
assertTrue(getActiveSession().isSecure());
assertTrue(FTPReply.isPositiveCompletion(client.noop()));
}
public void testReissueAuth() throws Exception {
assertTrue(getActiveSession().isSecure());
assertTrue(FTPReply.isPositiveCompletion(client.noop()));
// we do not accept reissued AUTH or AUTH on implicitly secured socket
assertEquals(534, client.sendCommand("AUTH SSL"));
}
public void testIsSecure() {
assertTrue(getActiveSession().isSecure());
}
public void testStoreWithProtPInPassiveMode() throws Exception {
client.setRemoteVerificationEnabled(false);
client.enterLocalPassiveMode();
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE1.exists());
assertEquals(TEST_DATA.length, TEST_FILE1.length());
}
public void testStoreWithProtPAndReturnToProtCInPassiveMode()
throws Exception {
client.setRemoteVerificationEnabled(false);
client.enterLocalPassiveMode();
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE1.exists());
assertEquals(TEST_DATA.length, TEST_FILE1.length());
((FTPSClient) client).execPROT("C");
assertFalse(getActiveSession().getDataConnection().isSecure());
client.storeFile(TEST_FILE2.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE2.exists());
assertEquals(TEST_DATA.length, TEST_FILE2.length());
}
public void testStoreWithProtPInActiveMode() throws Exception {
client.setRemoteVerificationEnabled(false);
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE1.exists());
assertEquals(TEST_DATA.length, TEST_FILE1.length());
}
public void testStoreWithProtPAndReturnToProtCInActiveMode()
throws Exception {
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
client.storeFile(TEST_FILE1.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE1.exists());
assertEquals(TEST_DATA.length, TEST_FILE1.length());
// needed due to bug in commons-net
client.setServerSocketFactory(null);
((FTPSClient) client).execPROT("C");
client.storeFile(TEST_FILE2.getName(), new ByteArrayInputStream(
TEST_DATA));
assertTrue(TEST_FILE2.exists());
assertEquals(TEST_DATA.length, TEST_FILE2.length());
}
public void testListEmptyDir() throws Exception {
client.enterLocalPassiveMode();
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
File dir = new File(ROOT_DIR, "dir");
dir.mkdir();
client.listFiles(dir.getName());
}
public void testReceiveEmptyFile() throws Exception {
client.enterLocalPassiveMode();
((FTPSClient) client).execPROT("P");
assertTrue(getActiveSession().getDataConnection().isSecure());
File file = new File(ROOT_DIR, "foo");
file.createNewFile();
InputStream is = null;
try {
is = client.retrieveFileStream(file.getName());
assertEquals(-1, is.read(new byte[1024]));
} finally {
IoUtils.close(is);
}
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ssl/ExplicitSecurityTestTemplate.java | Java | art | 5,752 |
/*
* 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;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class ImplicitSecurityTestTemplate extends
ExplicitSecurityTestTemplate {
protected boolean useImplicit() {
return true;
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/ssl/ImplicitSecurityTestTemplate.java | Java | art | 1,086 |
/*
* 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.usermanager.impl;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.apache.ftpserver.ftplet.Authentication;
import org.apache.ftpserver.ftplet.AuthenticationFailedException;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.UserManagerFactory;
import org.apache.ftpserver.usermanager.UsernamePasswordAuthentication;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class UserManagerTestTemplate extends TestCase {
protected UserManager userManager;
protected abstract UserManagerFactory createUserManagerFactory() throws Exception;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
userManager = createUserManagerFactory().createUserManager();
}
public void testAuthenticate() throws Exception {
assertNotNull(userManager
.authenticate(new UsernamePasswordAuthentication("user1", "pw1")));
}
public void testAuthenticateWrongPassword() throws Exception {
try {
userManager.authenticate(new UsernamePasswordAuthentication(
"user1", "foo"));
fail("Must throw AuthenticationFailedException");
} catch (AuthenticationFailedException e) {
// ok
}
}
public void testAuthenticateUnknownUser() throws Exception {
try {
userManager.authenticate(new UsernamePasswordAuthentication("foo",
"foo"));
fail("Must throw AuthenticationFailedException");
} catch (AuthenticationFailedException e) {
// ok
}
}
public void testAuthenticateEmptyPassword() throws Exception {
assertNotNull(userManager
.authenticate(new UsernamePasswordAuthentication("user3", "")));
}
public void testAuthenticateNullPassword() throws Exception {
assertNotNull(userManager
.authenticate(new UsernamePasswordAuthentication("user3", null)));
}
public static class FooAuthentication implements Authentication {
}
public void testAuthenticateNullUser() throws Exception {
try {
userManager.authenticate(new UsernamePasswordAuthentication(null,
"foo"));
fail("Must throw AuthenticationFailedException");
} catch (AuthenticationFailedException e) {
// ok
}
}
public void testAuthenticateUnknownAuthentication() throws Exception {
try {
userManager.authenticate(new FooAuthentication());
fail("Must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// ok
}
}
public void testDoesExist() throws Exception {
assertTrue(userManager.doesExist("user1"));
assertTrue(userManager.doesExist("user2"));
assertFalse(userManager.doesExist("foo"));
}
public void testGetAdminName() throws Exception {
assertEquals("admin", userManager.getAdminName());
}
public void testIsAdmin() throws Exception {
assertTrue(userManager.isAdmin("admin"));
assertFalse(userManager.isAdmin("user1"));
assertFalse(userManager.isAdmin("foo"));
}
public void testDelete() throws Exception {
assertTrue(userManager.doesExist("user1"));
assertTrue(userManager.doesExist("user2"));
userManager.delete("user1");
assertFalse(userManager.doesExist("user1"));
assertTrue(userManager.doesExist("user2"));
userManager.delete("user2");
assertFalse(userManager.doesExist("user1"));
assertFalse(userManager.doesExist("user2"));
}
public void testDeleteNonExistingUser() throws Exception {
// silent failure
userManager.delete("foo");
}
public void testGetUserByNameWithDefaultValues() throws Exception {
User user = userManager.getUserByName("user1");
assertEquals("user1", user.getName());
assertNull("Password must not be set", user.getPassword());
assertEquals("home", user.getHomeDirectory());
assertEquals(0, getMaxDownloadRate(user));
assertEquals(0, user.getMaxIdleTime());
assertEquals(0, getMaxLoginNumber(user));
assertEquals(0, getMaxLoginPerIP(user));
assertEquals(0, getMaxUploadRate(user));
assertNull(user.authorize(new WriteRequest()));
assertTrue(user.getEnabled());
}
public void testGetUserByName() throws Exception {
User user = userManager.getUserByName("user2");
assertEquals("user2", user.getName());
assertNull("Password must not be set", user.getPassword());
assertEquals("home", user.getHomeDirectory());
assertEquals(1, getMaxDownloadRate(user));
assertEquals(2, user.getMaxIdleTime());
assertEquals(3, getMaxLoginNumber(user));
assertEquals(4, getMaxLoginPerIP(user));
assertEquals(5, getMaxUploadRate(user));
assertNotNull(user.authorize(new WriteRequest()));
assertFalse(user.getEnabled());
}
public void testGetUserByNameWithUnknownUser() throws Exception {
assertNull(userManager.getUserByName("foo"));
}
private int getMaxDownloadRate(User user) {
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) user
.authorize(transferRateRequest);
if (transferRateRequest != null) {
return transferRateRequest.getMaxDownloadRate();
} else {
return 0;
}
}
private int getMaxUploadRate(User user) {
TransferRateRequest transferRateRequest = new TransferRateRequest();
transferRateRequest = (TransferRateRequest) user
.authorize(transferRateRequest);
if (transferRateRequest != null) {
return transferRateRequest.getMaxUploadRate();
} else {
return 0;
}
}
private int getMaxLoginNumber(User user) {
ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(
0, 0);
concurrentLoginRequest = (ConcurrentLoginRequest) user
.authorize(concurrentLoginRequest);
if (concurrentLoginRequest != null) {
return concurrentLoginRequest.getMaxConcurrentLogins();
} else {
return 0;
}
}
private int getMaxLoginPerIP(User user) {
ConcurrentLoginRequest concurrentLoginRequest = new ConcurrentLoginRequest(
0, 0);
concurrentLoginRequest = (ConcurrentLoginRequest) user
.authorize(concurrentLoginRequest);
if (concurrentLoginRequest != null) {
return concurrentLoginRequest.getMaxConcurrentLoginsPerIP();
} else {
return 0;
}
}
public void testSave() throws Exception {
BaseUser user = new BaseUser();
user.setName("newuser");
user.setPassword("newpw");
user.setHomeDirectory("newhome");
user.setEnabled(false);
user.setMaxIdleTime(2);
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
authorities.add(new ConcurrentLoginPermission(3, 4));
authorities.add(new TransferRatePermission(1, 5));
user.setAuthorities(authorities);
userManager.save(user);
User actualUser = userManager.getUserByName("newuser");
assertEquals(user.getName(), actualUser.getName());
assertNull(actualUser.getPassword());
assertEquals(user.getHomeDirectory(), actualUser.getHomeDirectory());
assertEquals(user.getEnabled(), actualUser.getEnabled());
assertNotNull(user.authorize(new WriteRequest()));
assertEquals(getMaxDownloadRate(user), getMaxDownloadRate(actualUser));
assertEquals(user.getMaxIdleTime(), actualUser.getMaxIdleTime());
assertEquals(getMaxLoginNumber(user), getMaxLoginNumber(actualUser));
assertEquals(getMaxLoginPerIP(user), getMaxLoginPerIP(actualUser));
assertEquals(getMaxUploadRate(user), getMaxUploadRate(actualUser));
// verify the password
assertNotNull(userManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw")));
try {
userManager.authenticate(new UsernamePasswordAuthentication("newuser", "dummy"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
// save without updating the users password (password==null)
userManager.save(user);
assertNotNull(userManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw")));
try {
userManager.authenticate(new UsernamePasswordAuthentication("newuser", "dummy"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
// save and update the users password
user.setPassword("newerpw");
userManager.save(user);
assertNotNull(userManager.authenticate(new UsernamePasswordAuthentication("newuser", "newerpw")));
try {
userManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
}
public void testSavePersistent() throws Exception {
BaseUser user = new BaseUser();
user.setName("newuser");
user.setPassword("newpw");
user.setHomeDirectory("newhome");
user.setEnabled(false);
user.setMaxIdleTime(2);
List<Authority> authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
authorities.add(new ConcurrentLoginPermission(3, 4));
authorities.add(new TransferRatePermission(1, 5));
user.setAuthorities(authorities);
userManager.save(user);
UserManager newUserManager = createUserManagerFactory().createUserManager();
User actualUser = newUserManager.getUserByName("newuser");
assertEquals(user.getName(), actualUser.getName());
assertNull(actualUser.getPassword());
assertEquals(user.getHomeDirectory(), actualUser.getHomeDirectory());
assertEquals(user.getEnabled(), actualUser.getEnabled());
assertNotNull(user.authorize(new WriteRequest()));
assertEquals(getMaxDownloadRate(user), getMaxDownloadRate(actualUser));
assertEquals(user.getMaxIdleTime(), actualUser.getMaxIdleTime());
assertEquals(getMaxLoginNumber(user), getMaxLoginNumber(actualUser));
assertEquals(getMaxLoginPerIP(user), getMaxLoginPerIP(actualUser));
assertEquals(getMaxUploadRate(user), getMaxUploadRate(actualUser));
// verify the password
assertNotNull(newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw")));
try {
newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "dummy"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
// save without updating the users password (password==null)
userManager.save(user);
newUserManager = createUserManagerFactory().createUserManager();
assertNotNull(newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw")));
try {
newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "dummy"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
// save and update the users password
user.setPassword("newerpw");
userManager.save(user);
newUserManager = createUserManagerFactory().createUserManager();
assertNotNull(newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "newerpw")));
try {
newUserManager.authenticate(new UsernamePasswordAuthentication("newuser", "newpw"));
fail("Must throw AuthenticationFailedException");
} catch(AuthenticationFailedException e) {
// ok
}
}
public void testSaveWithExistingUser() throws Exception {
BaseUser user = new BaseUser();
user.setName("user2");
user.setHomeDirectory("newhome");
userManager.save(user);
User actualUser = userManager.getUserByName("user2");
assertEquals("user2", actualUser.getName());
assertNull(actualUser.getPassword());
assertEquals("newhome", actualUser.getHomeDirectory());
assertEquals(0, getMaxDownloadRate(actualUser));
assertEquals(0, actualUser.getMaxIdleTime());
assertEquals(0, getMaxLoginNumber(actualUser));
assertEquals(0, getMaxLoginPerIP(actualUser));
assertEquals(0, getMaxUploadRate(actualUser));
assertNull(user.authorize(new WriteRequest()));
assertTrue(actualUser.getEnabled());
}
public void testSaveWithDefaultValues() throws Exception {
BaseUser user = new BaseUser();
user.setName("newuser");
user.setPassword("newpw");
userManager.save(user);
User actualUser = userManager.getUserByName("newuser");
assertEquals(user.getName(), actualUser.getName());
assertNull(actualUser.getPassword());
assertEquals("/", actualUser.getHomeDirectory());
assertEquals(true, actualUser.getEnabled());
assertNull(user.authorize(new WriteRequest()));
assertEquals(0, getMaxDownloadRate(actualUser));
assertEquals(0, actualUser.getMaxIdleTime());
assertEquals(0, getMaxLoginNumber(actualUser));
assertEquals(0, getMaxLoginPerIP(actualUser));
assertEquals(0, getMaxUploadRate(actualUser));
}
}
| zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/usermanager/impl/UserManagerTestTemplate.java | Java | art | 15,241 |
/*
* 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.impl;
import java.util.Date;
import junit.framework.TestCase;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>*
*/
public abstract class ServerFtpStatisticsTestTemplate extends TestCase {
public void testConnectionCount() {
ServerFtpStatistics stats = createStatistics();
assertEquals(0, stats.getTotalConnectionNumber());
assertEquals(0, stats.getCurrentConnectionNumber());
stats.setOpenConnection(new FtpIoSession(null, null));
assertEquals(1, stats.getTotalConnectionNumber());
assertEquals(1, stats.getCurrentConnectionNumber());
stats.setOpenConnection(new FtpIoSession(null, null));
assertEquals(2, stats.getTotalConnectionNumber());
assertEquals(2, stats.getCurrentConnectionNumber());
stats.setCloseConnection(new FtpIoSession(null, null));
assertEquals(2, stats.getTotalConnectionNumber());
assertEquals(1, stats.getCurrentConnectionNumber());
stats.setCloseConnection(new FtpIoSession(null, null));
assertEquals(2, stats.getTotalConnectionNumber());
assertEquals(0, stats.getCurrentConnectionNumber());
// This should never occure
stats.setCloseConnection(new FtpIoSession(null, null));
assertEquals(2, stats.getTotalConnectionNumber());
assertEquals(0, stats.getCurrentConnectionNumber());
}
@SuppressWarnings("deprecation")
public void testStartDateImmutable() {
ServerFtpStatistics stats = createStatistics();
Date date = stats.getStartTime();
date.setYear(1);
Date actual = stats.getStartTime();
assertFalse(1 == actual.getYear());
}
protected abstract DefaultFtpStatistics createStatistics();
} | zzh-simple-hr | Zftp/core/test/java/org/apache/ftpserver/impl/ServerFtpStatisticsTestTemplate.java | Java | art | 2,603 |
<head><script></script><title>Title</title> | zzh-simple-hr | Znekohtml/data/test042.html | HTML | art | 43 |
<html><head>
<span style="behavior:url(#default#clientCaps)" id=cc></span></head>
<body> | zzh-simple-hr | Znekohtml/data/test062.html | HTML | art | 90 |
<html>
<body>
<p>Here we go! <a href="http://bigidea.com/">Bob</a> <br/.</p>
and <a href="http://larryboy.com/"> Larry </a>
and friends <a href="http://google.com/">Google</a>
</body></html> | zzh-simple-hr | Znekohtml/data/test038.html | HTML | art | 201 |