📄 filerepository.java
字号:
/*
* Copyright (c) 2000-2005, University of Salford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the University of Salford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (c) 2006, University of Kent
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 1. Neither the name of the University of Kent nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.
*
* 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE
* IN THE CIRCUMSTANCES. IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS
* SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS
* SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH
* GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH
* TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY
* IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE
* SERIOUS FAULTS, IN THIS SOFTWARE.
*
* 5. This license is governed, except to the extent that local laws
* necessarily apply, by the laws of England and Wales.
*/
package issrg.utils.repository;
import issrg.utils.ParsedURL;
import issrg.utils.RFC2253NameParser;
import issrg.utils.RFC2253ParsingException;
import issrg.utils.ExceptionPairException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.directory.Attributes;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.BasicAttribute;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* This repository uses File URLs and the DN hash to find the attributes
* from an entry. The File URLs should be of the form:
* <pre>
* file://<path>[?<attribute type>=<file name mask>[&...]...]
* </pre>
* The path should normally point to the directory where the files are. However,
* it may point to a file, if a single file has to be used. (This may be useful
* when loading a Policy AC). The filename of the AC may not match the hash of
* the DN in this case. The path may be absolute or relative; in the latter case
* the path is computed from the current directory of the application.
*
* <p>The query
* part of the URL tells the FileRepository the mapping between the attribute
* types and file name mask (a regular expression). You should specify at least
* one attribute type mapping
* (a URL is meaningless otherwise - no attributes can be retrieved). However,
* if the query is omitted altogether,
* "?attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$"
* is assumed.
*
* <p>If the attribute type doesn't have the ";binary" suffix,
* the file is treated as a text file with one value in it, and it is returned
* as a string. Otherwise, a byte[] is the attribute value.
*
* <p>Example:
* <pre>
* file:///c:/certificates/?attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$&eduPerson=^.*\.edu$
* </pre>
*
* <p>This URL will tell the File Repository to look for
* attributeCertificateAttribute;binary in *.ace files, and look for
* userCertificate;binary attributes in *.cer files in c:/certificates/
* subdirectory.
*
* @author A.Otenko
*/
public class FileRepository extends DefaultRepository {
public static final String FILE_PROTOCOL="file";
/**
* Suffix used to name binary attributes. It is ";binary".
*/
public static final String BINARY_SUFFIX=";binary";
/**
* The default query assumed by the repository, if the query is omitted.
* Current value is: "attributeCertificateAttribute;binary=^.*\.ace$&userCertificate;binary=^.*\.cer$"
*/
public static final String DEFAULT_QUERY="attributeCertificateAttribute;binary=^.*\\.ace$&userCertificate;binary=^.*\\.cer$";
protected File rootDir;
protected File[] rootFile = new File[0];
protected Map typeMap = new Hashtable();
protected static final File[] systemRoots = File.listRoots();
protected int status=SUCCESS_STATUS;
protected RepositoryException diagnosis=null;
/**
* Constructs a File Repository given the URL as defined above.
*
* @param url - the file URL
*
* @throws RepositoryException, if the URL is not a valid file URL, or
* the path doesn't exist
*/
public FileRepository(String url) throws RepositoryException {
ParsedURL pu = ParsedURL.parseURL(url);
if (pu==null || !pu.getProtocol().toLowerCase().equals(FILE_PROTOCOL)){
throw new RepositoryException("A "+FILE_PROTOCOL+": URL expected, but "+url+" was found");
}
String path = pu.getHost()==null?"/":pu.getHost(); // the host name is not specified -> it starts with a slash
if (pu.getPathString()!=null) path = path+"/"+pu.getPathString(); // even if path is a slash, we can still add a slash - two slashes are allowed
rootDir = new File(path);
if (!rootDir.exists()){
throw new RepositoryException("Bad URL: "+url+" - "+pu.getPathString()+" must be a file or directory that exists");
}
if (rootDir.isFile()){
rootFile = new File[]{rootDir};
}
String query = pu.getQuery();
if (query==null) query=DEFAULT_QUERY;
query=query+"&"; // append "&", so type mapping always ends with it
for (int i=0, j=0; (j=query.indexOf("&", i))>=0; i=j+1){ // while there are any "&"
String q = query.substring(i, j);
int k=q.indexOf("="); // the sign separating the attribute type from the file mask
if (k<0 || k>=q.length()-1){
throw new RepositoryException(url+" URL has an invalid attribute type mapping: "+pu.getQuery()+" @ "+i);
}
String type = q.substring(0, k);
String mask = q.substring(k+1);
Pattern p = Pattern.compile(mask);
typeMap.put(type, p);
}
//System.out.println("File Repository: "+rootDir.getAbsolutePath()+", type mapping: "+typeMap); //************
}
/**
* This method is called by getAttribute and getAllAttributes methods and
* returns the attributes named, or all attributes, if no attribute names
* were provided.
*
* @param dn - the name of the entry; FileRepository assumes they are
* RFC2253-compliant LDAP DNs
* @param attributes - the list of attribute names to return; if the
* array is null, all available attributes are returned from the entry
*
* @return Attributes filled with the attributes requested, or null, if
* there was a problem (getStatus will return FAILURE_STATUS)
*/
public Attributes getAttributes(Principal dn, String [] attributes) throws RepositoryException {
try{
try{
status = FAILURE_STATUS;
if (attributes==null){ // get all the attributes
attributes = (String[])typeMap.keySet().toArray(new String[0]);
}
// attributes is not null now
Attributes result = new BasicAttributes();
File[] files = rootDir.isFile()?
rootFile:
rootDir.listFiles(new Filter(dn.getName()));
if (files==null){ // it may be null, if an IO error occured
throw new RepositoryException("Failed to list files in directory "+rootDir.getAbsolutePath());
}
ExceptionPairException pe=null;
for (int i=0; i<attributes.length; i++){
boolean binary = attributes[i].endsWith(BINARY_SUFFIX);
Pattern mask = (Pattern)typeMap.get(attributes[i]); // get the corresponding mask
if (mask==null){
mask = (Pattern)typeMap.get(attributes[i]+";binary"); // try to see if the ";binary" suffix was omitted in the attribute name
binary=true; // if the mask is not null, the attributes will be treated as binary, even though they don't have the suffix explicitly
}
if (mask==null) continue; // skip this attribute, if no mask is defined for it
Attribute attr = null;
for (int j=0; j<files.length; j++){
//System.out.println("Matching "+files[j].getName()+" against "+mask.pattern()+": "+mask.matcher(files[j].getName()).matches()); //************
if (!mask.matcher(files[j].getName()).matches()) continue; // this file does not contain data for the attribute
try{
long len = files[j].length();
if (len>0x0ffffffffL){
throw new RepositoryException("File "+files[j].getAbsolutePath()+" is too long: "+len);
}
//System.out.print("Reading file "+files[i].getName()+"..."); //************
byte [] content = new byte[(int)(len & 0xffffffff)]; // make space for the whole file
FileInputStream fis = new FileInputStream(files[j]);
fis.read(content); // TODO: need to check if the whole file has been actually read; this is unlikely, though
fis.close();
if (attr==null) attr=new BasicAttribute(attributes[i]);
Object value=binary?(Object)content: (Object)new String(content);
if (!attr.add(value)){
throw new RepositoryException("Failed to add a value read from file "+files[i].getAbsolutePath());
}
//System.out.println("done."); //************
}catch (Throwable ioe){
// set status to PARTIAL_SUCCESS, if pe!=null
pe = new ExceptionPairException(ioe, pe);
}
}
if (attr!=null) { // then it has some values
result.put(attr);
status = SUCCESS_STATUS;
}
}
/*
* now if status = FAILURE, then no attribute was successfully read.
* This may mean two things: pe==null - no attributes are in the entry - status=SUCCESS
* pe!=null - all reads failed - status=FAILURE
*
* if status = SUCCESS, then some attributes read successfully.
* Then if pe==null, all attributes read successfully, status=SUCCESS
* pe!=null - some attributes failed to read, status=PARTIAL_SUCCESS
*/
if (status==FAILURE_STATUS && pe==null){ // successfully read empty entry
status=SUCCESS_STATUS;
}
if (status==SUCCESS_STATUS && pe!=null){ // failed to read some of the attributes
status=PARTIAL_SUCCESS_STATUS;
}
if (status==FAILURE_STATUS) result=null;
return result;
}catch(RepositoryException re){ // forward RepositoryExceptions, ...
throw re;
}catch(Throwable th){ // wrap any other exceptions into RepositoryExceptions
throw new RepositoryException("Unknown error", th);
}
}catch(RepositoryException re){
diagnosis = re;
status=FAILURE_STATUS;
throw re;
}
}
public int getStatus(){
return status;
}
public Throwable getDiagnosis(){
return diagnosis;
}
}
/**
* This is the filter used to gather only the files that belong to the given
* user. It uses a hash of the canonical LDAP DN to match the filenames.
*/
class Filter implements FilenameFilter {
String entry;
/**
* This constructor builds a Filter for a given LDAP DN. The DN is
* canonicalised first, then the hash of the resulting string is
* computed. It is assumed that the files from the entry with the given
* DN will have this hash in their filename, so only these files match
* the Filter.
*
* @param entry - the LDAP DN of the entry; can be a non-canonical DN
*/
public Filter (String entry){
byte [] hash = issrg.ac.Util.hashDN(entry);
if (hash==null) hash = issrg.ac.Util.hashString(entry);
this.entry = issrg.ac.Util.hashToString(hash);
// now entry is the hash to look for in the filenames.
//System.out.println("Will search for "+entry+" -> "+this.entry); //**********
}
/**
* This method tests if the specified file matches the DN. Only files
* containing the hash of the entry DN in the filename are accepted.
* Directories are ignored.
*
* @param dir - the File of the parent directory containing the file
* @param name - the name of the file in question
*
* @return true, if the file is not a directory and contains the hash of
* the canonical DN in the filename
*/
public boolean accept(File dir, String name){
//System.out.println("\taccept file "+name+": "+(new File(dir, name).isFile() && name.indexOf(entry)>=0)+" - "+entry); //***********
return new File(dir, name).isFile() && name.indexOf(entry)>=0;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -