/* WCEKeyManagerFactorySpi.java
   Copyright (C) 2009 Mysaifu.com

This file is a part of Mysaifu JVM.

Mysaifu JVM is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

Mysaifu JVM is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mysaifu JVM; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package com.mysaifu.jvm.java.security.provider;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactorySpi;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.ManagerFactoryParameters;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * KeyManagerFactory for Windows CE.
 */
public class WCEKeyManagerFactorySpi
    extends KeyManagerFactorySpi
{
  /**
   * キーストア
   */
  private KeyStore keyStore;

  /**
   * パスワード
   */
  private char[] password;

  @Override
  protected void engineInit(KeyStore ks, char[] password)
      throws KeyStoreException, NoSuchAlgorithmException,
      UnrecoverableKeyException
  {
    if (ks == null)
      {
        // システムプロパティを読み込み、KeyStoreを作成する
        String keyStoreType = AccessController.doPrivileged(new PrivilegedAction<String>()
        {
          public String run()
          {
            return System.getProperty("javax.net.ssl.keyStoreType");
          }
        });
        if (keyStoreType == null)
          {
            keyStoreType = KeyStore.getDefaultType();
          }

        // キーストアファイル
        String keyStoreFile = AccessController.doPrivileged(new PrivilegedAction<String>()
        {
          public String run()
          {
            return System.getProperty("javax.net.ssl.keyStore");
          }
        });

        // パスワード
        String pass = AccessController.doPrivileged(new PrivilegedAction<String>()
        {
          public String run()
          {
            return System.getProperty("javax.net.ssl.keyStorePassword");
          }
        });

        ks = KeyStore.getInstance(keyStoreType);
        // キーストアファイルから読み込む
        InputStream ins = null;
        try
          {
            if (keyStoreFile != null)
              {
                ins = new BufferedInputStream(new FileInputStream(keyStoreFile));
              }
            ks.load(ins, pass != null ? pass.toCharArray() : null);
          }
        catch (IOException ioe)
          {
            throw new KeyStoreException(ioe);
          }
        catch (CertificateException ce)
          {
            throw new KeyStoreException(ce);
          }

      }
    this.keyStore = ks;

    // パスワードは使わない
    // this.password = (char[]) password.clone();
  }

  @Override
  protected void engineInit(ManagerFactoryParameters spec)
      throws InvalidAlgorithmParameterException
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  protected KeyManager[] engineGetKeyManagers()
  {
    return new KeyManager[] { getDefaultKeyManager() };
  }

  /**
   * デフォルトの鍵マネージャを返す。
   */
  X509ExtendedKeyManager getDefaultKeyManager()
  {
    return new WCEKeyManager();
  }

  /**
   * 鍵マネージャ
   */
  private class WCEKeyManager
      extends X509ExtendedKeyManager
  {
    /**
     * KeyStore内の全エイリアス
     */
    private String[] aliases;

    WCEKeyManager()
    {
      try
        {
          Enumeration<String> e = WCEKeyManagerFactorySpi.this.keyStore.aliases();
          List<String> list = new ArrayList<String>();
          while (e.hasMoreElements())
            {
              list.add(e.nextElement());
            }
          this.aliases = list.toArray(new String[list.size()]);
        }
      catch (KeyStoreException kse)
        {
          this.aliases = new String[0];
          kse.printStackTrace();
        }
    }

    @Override
    public String[] getClientAliases(String keyType, Principal[] issuers)
    {
      // KeyStore内の全エイリアスを返す
      return (String[]) this.aliases.clone();
    }

    @Override
    public String chooseClientAlias(String[] keyType, Principal[] issuers,
                                    Socket socket)
    {
      // 先頭のエイリアスを返す
      if (this.aliases.length > 0)
        {
          return aliases[0];
        }
      return null;
    }

    @Override
    public String[] getServerAliases(String keyType, Principal[] issuers)
    {
      // KeyStore内の全エイリアスを返す
      return (String[]) this.aliases.clone();
    }

    @Override
    public String chooseServerAlias(String keyType, Principal[] issuers,
                                    Socket socket)
    {
      // 先頭のエイリアスを返す
      if (this.aliases.length > 0)
        {
          return aliases[0];
        }
      return null;
    }

    @Override
    public X509Certificate[] getCertificateChain(String alias)
    {
      X509Certificate[] result = null;
      try
        {
          Certificate[] certs = WCEKeyManagerFactorySpi.this.keyStore.getCertificateChain(alias);
          if (certs != null)
            {
              X509Certificate[] tmp = new X509Certificate[certs.length];
              for (int i = 0; i < certs.length; ++i)
                {
                  if (! (certs[i] instanceof X509Certificate))
                    {
                      break;
                    }
                  tmp[i] = (X509Certificate) certs[i];
                }
              result = tmp;
            }
        }
      catch (KeyStoreException kse)
        {
          kse.printStackTrace();
        }
      return result;
    }

    @Override
    public PrivateKey getPrivateKey(String alias)
    {
      throw new UnsupportedOperationException("Not implemented");
    }
  }
}
