Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: CPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Common Public License Version 1.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.eclipse.org/legal/cpl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2006 Ola Bini <ola@ologix.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the CPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the CPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.ext.openssl.x509store;
 
 import java.io.File;
 import java.io.Reader;
 
 
 
 import java.util.List;
 import org.jruby.Ruby;
 
X509_LOOKUP

Author(s):
Ola Bini
 
 public class Lookup {
     public boolean init;
     public boolean skip;
     public LookupMethod method;
     public Object methodData;
     public Store store;

    
c: X509_LOOKUP_new
 
     public Lookup(LookupMethod methodthrows Exception {
         =false;
         =false;
         this.=method;
         =null;
         =null;
         if(method.newItem != null && method.newItem != . && method.newItem.call(this) == 0) {
             throw new Exception();
         }
     }

    
c: X509_LOOKUP_load_file
 
     public int loadFile(CertificateFile.Path filethrows Exception {
         return control(.,file.name,file.type,null);
     }

    
c: X509_LOOKUP_add_dir
 
     public int addDir(CertificateHashDir.Dir dirthrows Exception {
         return control(.,dir.name,dir.type,null);
     }

    
c: X509_LOOKUP_hash_dir
    public static LookupMethod hashDirLookup() { 
        return ;
    } 

    
c: X509_LOOKUP_file
    public static LookupMethod fileLookup() { 
        return ;
    }

    
c: X509_LOOKUP_ctrl
    public int control(int cmdString argclong arglString[] retthrows Exception {
        if( == null) {
            return -1;
        }
        if(. != null && . != .) {
            return ..call(this,new Integer(cmd),argc,new Long(argl),ret);
        } else {
            return 1;
        }
    }

    
c: X509_LOOKUP_load_cert_file
    public int loadCertificateFile(String fileint typethrows Exception {
        if (file == null) {
            return 1;
        }
        int count = 0;
        int ret = 0;
        Reader reader = null;
        try {
            InputStream in = wrapJRubyNormalizedInputStream(file);
            X509AuxCertificate x = null;
            if (type == .) {
                reader = new BufferedReader(new InputStreamReader(in));
                for (;;) {
                    x = PEMInputOutput.readX509Aux(readernull);
                    if (null == x) {
                        break;
                    }
                    int i = .addCertificate(x);
                    if (i == 0) {
                        return ret;
                    }
                    count++;
                    x = null;
                }
                ret = count;
            } else if (type == .) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                x = StoreContext.ensureAux((X509Certificatecf.generateCertificate(in));
                if (x == null) {
                    X509Error.addError(13);
                    return ret;
                }
                int i = .addCertificate(x);
                if (i == 0) {
                    return ret;
                }
                ret = i;
            } else {
                X509Error.addError(.);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception ignored) {
                }
            }
        }
        return ret;
    }

    
c: X509_LOOKUP_load_crl_file
    public int loadCRLFile(String fileint typethrows Exception {
        if (file == null) {
            return 1;
        }
        int count = 0;
        int ret = 0;
        Reader reader = null;
        try {
            InputStream in = wrapJRubyNormalizedInputStream(file);
            CRL x = null;
            if (type == .) {
                reader = new BufferedReader(new InputStreamReader(in));
                for (;;) {
                    x = PEMInputOutput.readX509CRL(readernull);
                    if (null == x) {
                        break;
                    }
                    int i = .addCRL(x);
                    if (i == 0) {
                        return ret;
                    }
                    count++;
                    x = null;
                }
                ret = count;
            } else if (type == .) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                x = cf.generateCRL(in);
                if (x == null) {
                    X509Error.addError(13);
                    return ret;
                }
                int i = .addCRL(x);
                if (i == 0) {
                    return ret;
                }
                ret = i;
            } else {
                X509Error.addError(.);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception ignored) {
                }
            }
        }
        return ret;
    }

    
c: X509_LOOKUP_load_cert_crl_file
    public int loadCertificateOrCRLFile(String fileint typethrows Exception {
        if (type != .) {
            return loadCertificateFile(filetype);
        }
        int count = 0;
        Reader reader = null;
        try {
            InputStream in = wrapJRubyNormalizedInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in));
            for (;;) {
                Object v = PEMInputOutput.readPEM(readernull);
                if (null == v) {
                    break;
                }
                if (v instanceof X509Certificate) {
                    .addCertificate(StoreContext.ensureAux((X509Certificatev));
                    count++;
                } else if (v instanceof CRL) {
                    .addCRL((CRLv);
                    count++;
                }
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception ignored) {
                }
            }
        }
        return count
    }
    public int loadDefaultJavaCACertsFile() throws Exception {
        int count = 0;
        String certsFile = System.getProperty("java.home") + "/lib/security/cacerts".replace('/'.);
        FileInputStream fin = new FileInputStream(certsFile);
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            // we pass a null password, as the cacerts file isn't password protected
            keystore.load(finnull);
            PKIXParameters params = new PKIXParameters(keystore);
            for(TrustAnchor trustAnchor : params.getTrustAnchors()) {
                X509Certificate certificate = trustAnchor.getTrustedCert();
                .addCertificate(certificate);
                count++;
            }    
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (Exception ignored) {
                }
            }
        }
        return count;
    }
        Ruby runtime = Ruby.getGlobalRuntime();
        try {
            ChannelDescriptor descriptor = ChannelDescriptor.open(runtime.getCurrentDirectory(), filenew ModeFlags(.));
            return ChannelStream.open(runtimedescriptor).newInputStream();
        } catch (NoSuchMethodError nsme) {
            return new BufferedInputStream(new FileInputStream(file));
        } catch (FileExistsException fee) {
            // should not happen because ModeFlag does not contain CREAT.
            fee.printStackTrace(.);
            throw new IllegalStateException(fee.getMessage(), fee);
        } catch (InvalidValueException ive) {
            // should not happen because ModeFlasg does not contain APPEND.
            ive.printStackTrace(.);
            throw new IllegalStateException(ive.getMessage(), ive);
        }
    }

    
c: X509_LOOKUP_free
    public void free() throws Exception {
        if( != null && . != null && . != .) {
            ..call(this);
        }
    }

    
c: X509_LOOKUP_init
    public int init() throws Exception { 
        if( == null) {
            return 0;
        }
        if(. != null && . != .) {
            return ..call(this);
        }
        return 1;
    }

    
c: X509_LOOKUP_by_subject
    public int bySubject(int typeName name,X509Object[] retthrows Exception { 
        if( == null || . == null || . == .) {
            return .;
        }
        if() {
            return 0;
        }
        return ..call(this,new Integer(type),name,ret);
    }

    
c: X509_LOOKUP_by_issuer_serial
    public int byIssuerSerialNumber(int typeName name,BigInteger serialX509Object[] retthrows Exception { 
        if( == null || . == null || . == .) {
            return .;
        }
        return ..call(this,new Integer(type),name,serial,ret);
    } 

    
c: X509_LOOKUP_by_fingerprint
    public int byFingerprint(int type,String bytesX509Object[] retthrows Exception { 
        if( == null || . == null || . == .) {
            return .;
        }
        return ..call(this,new Integer(type),bytes,ret);
    } 

    
c: X509_LOOKUP_by_alias
    public int byAlias(int typeString strX509Object[] retthrows Exception { 
        if( == null || . == null || . == .) {
            return .;
        }
        return ..call(this,new Integer(type),str,ret);
    } 

    
c: X509_LOOKUP_shutdown
    public int shutdown() throws Exception { 
        if( == null) {
            return 0;
        }
        if(. != null && . != .) {
            return ..call(this);
        }
        return 1;
    }

    
c: x509_file_lookup
    private final static LookupMethod x509FileLookup = new LookupMethod();

    
c: x509_dir_lookup
    private final static LookupMethod x509DirectoryLookup = new LookupMethod();
    static {
        . = "Load file into cache";
        . = new ByFile();
        . = "Load certs from files in a directory";
        . = new NewLookupDir();
        . = new FreeLookupDir();
        . = new LookupDirControl();
    }
    
    
c: by_file_ctrl
    private static class ByFile implements LookupMethod.ControlFunction {
        public int call(Object _ctxObject _cmdObject _argpObject _arglObject _retthrows Exception {
            Lookup ctx = (Lookup)_ctx;
            int cmd = ((Integer)_cmd).intValue();
            String argp = (String)_argp;
            long argl = ((Long)_argl).longValue();
            int ok = 0;
            String file = null;
            
            switch(cmd) {
            case .:
                if (argl == .) {
                    try {
                        RubyHash env = (RubyHash)Ruby.getGlobalRuntime().getObject().getConstant("ENV");
                        file = (String)env.get(Ruby.getGlobalRuntime().newString(X509Utils.getDefaultCertificateFileEnvironment()));
                    } catch (Error error) {
                    }
                    if (file != null) {
                        ok = ctx.loadCertificateOrCRLFile(file.) != 0 ? 1 : 0;
                    } else {
                        ok = (ctx.loadDefaultJavaCACertsFile() != 0) ? 1: 0;
                    }
                    if (ok == 0) {
                        X509Error.addError(.);
                    }
                } else {
                    if (argl == .) {
                        ok = (ctx.loadCertificateOrCRLFile(argp.) != 0) ? 1 : 0;
                    } else {
                        ok = (ctx.loadCertificateFile(argp, (intargl) != 0) ? 1 : 0;
                    }
                }
                break;
            }
            return ok;
        }
    }

    
c: BY_DIR, lookup_dir_st
    private static class LookupDir {
        List<Stringdirs;
        List<IntegerdirsType;
    }

    
c: new_dir
    private static class NewLookupDir implements LookupMethod.NewItemFunction {
        public int call(Object _lu) {
            Lookup lu = (Lookup)_lu;
            LookupDir a = new LookupDir();
            a.dirs = new ArrayList<String>();
            a.dirsType = new ArrayList<Integer>();
            lu.methodData = a;
            return 1;
        }
    }

    
c: free_dir
    private static class FreeLookupDir implements LookupMethod.FreeFunction {
        public int call(Object _lu) {
            Lookup lu = (Lookup)_lu;
            LookupDir a = (LookupDir)lu.methodData;
            a.dirs = null;
            a.dirsType = null;
            lu.methodData = null;
            return -1;
        }
    }

    
c: dir_ctrl
    private static class LookupDirControl implements LookupMethod.ControlFunction {
        public int call(Object _ctxObject _cmdObject _argpObject _arglObject _retp) {
            Lookup ctx = (Lookup)_ctx;
            int cmd = ((Integer)_cmd).intValue();
            String argp = (String)_argp;
            long argl = ((Long)_argl).longValue();
            int ret = 0;
            LookupDir ld = (LookupDir)ctx.methodData;
            String dir = null;
            switch(cmd) {
            case .:
                if(argl == .) {
                    try {
                        RubyHash env = (RubyHash)Ruby.getGlobalRuntime().getObject().getConstant("ENV");
                        dir = (String)env.get(Ruby.getGlobalRuntime().newString(X509Utils.getDefaultCertificateDirectoryEnvironment()));
                    } catch (Error error) {
                    }
                    if(null != dir) {
                        ret = addCertificateDirectory(ld,dir,.);
                    } else {
                        ret = addCertificateDirectory(ld,X509Utils.getDefaultCertificateDirectory(),.);
                    }
                    if(ret == 0) {
                        X509Error.addError(.);
                    }
                } else {
                    ret = addCertificateDirectory(ld,argp,(int)argl);
                }
                break;
            }
            return ret;
        }

        
c: add_cert_dir
        private int addCertificateDirectory(LookupDir ctx,String dir,int type) {
            if(dir == null || "".equals(dir)) {
                X509Error.addError(.);
                return 0;
            }
            String[] dirs = dir.split(System.getProperty("path.separator"));
            for(int i=0;i<dirs.length;i++) {
                if(dirs[i].length() == 0) {
                    continue;
                }
                if(ctx.dirs.contains(dirs[i])) {
                    continue;
                }
                ctx.dirsType.add(type);
                ctx.dirs.add(dirs[i]);
            }
            return 1;
        }
    }

    
c: get_cert_by_subject
    private static class GetCertificateBySubject implements LookupMethod.BySubjectFunction {
        public int call(Object _xlObject _typeObject _nameObject _retthrows Exception {
            Lookup x1 = (Lookup)_xl;
            int type = ((Integer)_type).intValue();
            Name name = (Name)_name;
            X509Object[] ret = (X509Object[])_ret;
            int ok = 0;
            StringBuffer b = new StringBuffer();
            if(null == name) {
                return 0;
            }
            String postfix = "";
            if(type == .) {
            } else if(type == .) {
                postfix = "r";
            } else {
                X509Error.addError(.);
                return ok;
            }
            
            LookupDir ctx = (LookupDir)x1.methodData;
            long h = name.hash();
            
            Iterator<Integeriter = ctx.dirsType.iterator();
            for(String cdir : ctx.dirs) {
                int tp = iter.next();
                int k = 0;
                for(;;) {
                    b.append(String.format("%s%s%08x.%s%d"cdir.hpostfixk));
                    k++;
                    if(!(new File(b.toString()).exists())) {
                        break;
                    }
                    if(type == .) {
                        if((x1.loadCertificateFile(b.toString(),tp)) == 0) {
                            break;
                        }
                    } else if(type == .) {
                        if((x1.loadCRLFile(b.toString(),tp)) == 0) {
                            break;
                        }
                    }
                }
                X509Object tmp = null;
                synchronized(.) {
                    for(X509Object o : x1.store.objs) {
                        if(o.type() == type && o.isName(name)) {
                            tmp = o;
                            break;
                        }
                    }
                }
                if(tmp != null) {
                    ok = 1;
                    ret[0] = tmp;
                    break;
                }
            }
            return ok;
        }
    }
}// X509_LOOKUP
New to GrepCode? Check out our FAQ X