"""M2Crypto wrapper for OpenSSL X509 API.

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.

Portions created by Open Source Applications Foundation (OSAF) are
Copyright (C) 2004-2007 OSAF. All Rights Reserved.
Author: Heikki Toivonen
"""

# M2Crypto
from M2Crypto import ASN1, BIO, Err, EVP, util
import m2

FORMAT_DER = 0
FORMAT_PEM = 1

class X509Error(Exception): pass

m2.x509_init(X509Error)

V_OK = m2.X509_V_OK

def new_extension(name, value, critical=0, _pyfree=1):
    """
    Create new X509_Extension instance.
    """
    if name == 'subjectKeyIdentifier' and \
        value.strip('0123456789abcdefABCDEF:') is not '':
        raise ValueError('value must be precomputed hash')
    lhash = m2.x509v3_lhash()
    ctx = m2.x509v3_set_conf_lhash(lhash)
    x509_ext_ptr = m2.x509v3_ext_conf(lhash, ctx, name, value)
    x509_ext = X509_Extension(x509_ext_ptr, _pyfree)
    x509_ext.set_critical(critical)
    return x509_ext 


class X509_Extension:
    """
    X509 Extension
    """
    
    m2_x509_extension_free = m2.x509_extension_free
    
    def __init__(self, x509_ext_ptr=None, _pyfree=1):
        self.x509_ext = x509_ext_ptr
        self._pyfree = _pyfree

    def __del__(self):
        if getattr(self, '_pyfree', 0) and self.x509_ext:
            self.m2_x509_extension_free(self.x509_ext)

    def _ptr(self):
        return self.x509_ext

    def set_critical(self, critical=1):
        """
        Mark this extension critical or noncritical. By default an
        extension is not critical.

        @type critical:  int
        @param critical: Nonzero sets this extension as critical.
                         Calling this method without arguments will
                         set this extension to critical.
        """
        return m2.x509_extension_set_critical(self.x509_ext, critical)
    
    def get_critical(self):
        """
        Return whether or not this is a critical extension.

        @rtype:   int
        @return:  Nonzero if this is a critical extension.
        """
        return m2.x509_extension_get_critical(self.x509_ext)
    
    def get_name(self):
        """
        Get the extension name, for example 'subjectAltName'.
        """
        return m2.x509_extension_get_name(self.x509_ext)

    def get_value(self, flag=0, indent=0):
        """
        Get the extension value, for example 'DNS:www.example.com'.
        
        @param flag:   Flag to control what and how to print.
        @param indent: How many spaces to print before actual value.
        """
        buf=BIO.MemoryBuffer()
        m2.x509_ext_print(buf.bio_ptr(), self.x509_ext, flag, indent)
        return buf.read_all()    


class X509_Extension_Stack:
    """
    X509 Extension Stack
    
    @warning: Do not modify the underlying OpenSSL stack
    except through this interface, or use any OpenSSL functions that do so
    indirectly. Doing so will get the OpenSSL stack and the internal pystack
    of this class out of sync, leading to python memory leaks, exceptions
    or even python crashes!
    """

    m2_sk_x509_extension_free = m2.sk_x509_extension_free

    def __init__(self, stack=None, _pyfree=0):
        if stack is not None:
            self.stack = stack
            self._pyfree = _pyfree
            num = m2.sk_x509_extension_num(self.stack)
            for i in range(num):
                self.pystack.append(X509_Extension(m2.sk_x509_extension_value(self.stack, i),
                                                   _pyfree=_pyfree))
        else:
            self.stack = m2.sk_x509_extension_new_null()
            self._pyfree = 1
            self.pystack = [] # This must be kept in sync with self.stack
        
    def __del__(self):
        if getattr(self, '_pyfree', 0):
            self.m2_sk_x509_extension_free(self.stack)

    def __len__(self):
        assert m2.sk_x509_extension_num(self.stack) == len(self.pystack)
        return len(self.pystack)

    def __getitem__(self, idx):
        return self.pystack[idx]
    
    def __iter__(self):
        return iter(self.pystack)
 
    def _ptr(self):
        return self.stack

    def push(self, x509_ext):
        """
        Push X509_Extension object onto the stack.

        @type x509_ext: M2Crypto.X509.X509_Extension
        @param x509_ext: X509_Extension object to be pushed onto the stack.
        @return: The number of extensions on the stack.
        """
        self.pystack.append(x509_ext)
        ret = m2.sk_x509_extension_push(self.stack, x509_ext._ptr())
        assert ret == len(self.pystack)
        return ret

    def pop(self):
        """
        Pop X509_Extension object from the stack.
        
        @return: X509_Extension popped
        """
        x509_ext_ptr = m2.sk_x509_extension_pop(self.stack)
        if x509_ext_ptr is None:
            assert len(self.pystack) == 0
            return None
        return self.pystack.pop()


class X509_Name_Entry:
    """
    X509 Name Entry
    """

    m2_x509_name_entry_free = m2.x509_name_entry_free

    def __init__(self, x509_name_entry, _pyfree=0):
        self.x509_name_entry = x509_name_entry
        self._pyfree = _pyfree
        
    def __del__(self):
        if getattr
(self, '_pyfree', 0):
            self.m2_x509_name_entry_free(self.x509_name_entry)

    def _ptr(self):
        return self.x509_name_entry

    def set_object(self, asn1obj):
        return m2.
x509_name_entry_set_object(self.x509_name_entry,
                                             asn1obj._ptr())

    def set_data(self, data, type=ASN1.MBSTRING_ASC):
        return m2.x509_name_entry_set_data(self.x509_name_entry,
                                           type, data)

    def get_object(self):
        return ASN1.ASN1_Object(m2.x509_name_entry_get_object(self.x509_name_entry))
        
    def get_data(self):
        return ASN1.ASN1_String(m2.x509_name_entry_get_data(self.x509_name_entry))

    def create_by_txt( self, field, type, entry, len):
        return m2.x509_name_entry_create_by_txt(self.x509_name_entry._ptr(),
                                                field, type, entry, len)
    

class X509_Name:
    """
    X509 Name
    """

    nid = {'C'                      : m2.NID_countryName,
           'SP'                     : m2.NID_stateOrProvinceName,
           'ST'                     : m2.NID_stateOrProvinceName,
           'stateOrProvinceName'    : m2.NID_stateOrProvinceName,
           'L'                      : m2.NID_localityName,
           'localityName'           : m2.NID_localityName,
           'O'                      : m2.NID_organizationName,
           'organizationName'       : m2.NID_organizationName,
           'OU'                     : m2.NID_organizationalUnitName,
           'organizationUnitName'   : m2.NID_organizationalUnitName,
           'CN'                     : m2.NID_commonName,
           'commonName'             : m2.NID_commonName,
           'Email'                  : m2.NID_pkcs9_emailAddress,
           'emailAddress'           : m2.NID_pkcs9_emailAddress,
           'serialNumber'           : m2.NID_serialNumber,
           'SN'                     : m2.NID_surname,
           'surname'                : m2.NID_surname,
           'GN'                     : m2.NID_givenName,
           'givenName'              : m2.NID_givenName
           }

    m2_x509_name_free = m2.x509_name_free

    def __init__(self, x509_name=None, _pyfree=0):
        if x509_name is not None:
            assert m2.x509_name_type_check(x509_name), "'x509_name' type error"
            self.x509_name = x509_name
            self._pyfree = _pyfree
        else:
            self.x509_name = m2.x509_name_new ()
            self._pyfree = 1
            
    def __del__(self):
        if getattr(self, '_pyfree', 0):
            self.m2_x509_name_free(self.x509_name)

    def __str__(self):
        assert m2.x509_name_type_check(self.x509_name), "'x509_name' type error" 
        return m2.x509_name_oneline(self.x509_name)

    def __getattr__(self, attr):
        if attr in self.nid:
            assert m2.x509_name_type_check(self.x509_name), "'x509_name' type error" 
         