pkcs12BagAttrs.cpp [plain text]
#include "pkcs12BagAttrs.h"
#include "pkcs12Utils.h"
#include <security_asn1/nssUtils.h>
#include <assert.h>
#include <Security/SecBase.h>
P12BagAttrs::P12BagAttrs(
const P12BagAttrs *otherAttrs,
SecNssCoder &coder)
: mAttrs(NULL), mCoder(coder)
{
if(otherAttrs == NULL) {
return;
}
unsigned num = otherAttrs->numAttrs();
reallocAttrs(num);
for(unsigned dex=0; dex<num; dex++) {
copyAttr(*otherAttrs->mAttrs[dex], *mAttrs[dex]);
}
}
unsigned P12BagAttrs::numAttrs() const
{
return nssArraySize((const void **)mAttrs);
}
NSS_Attribute *P12BagAttrs::getAttr(
unsigned attrNum)
{
assert(attrNum < numAttrs());
return mAttrs[attrNum];
}
void P12BagAttrs::addAttr(
const NSS_Attribute &attr)
{
NSS_Attribute *newAttr = reallocAttrs(numAttrs() + 1);
copyAttr(attr, *newAttr);
}
void P12BagAttrs::addAttr(
const CFDataRef attrOid,
const CFArrayRef attrValues)
{
NSS_Attribute *newAttr = reallocAttrs(numAttrs() + 1);
p12CfDataToCssm(attrOid, newAttr->attrType, mCoder);
uint32 numVals = (uint32)CFArrayGetCount(attrValues);
newAttr->attrValue = (CSSM_DATA **)p12NssNullArray(numVals, mCoder);
for(unsigned dex=0; dex<numVals; dex++) {
CSSM_DATA *dstVal = (CSSM_DATA *)mCoder.malloc(sizeof(CSSM_DATA));
newAttr->attrValue[dex] = dstVal;
CFDataRef srcVal = (CFDataRef)CFArrayGetValueAtIndex(attrValues, dex);
assert(CFGetTypeID(srcVal) == CFDataGetTypeID());
p12CfDataToCssm(srcVal, *dstVal, mCoder);
}
}
void P12BagAttrs::getAttr(
unsigned attrNum,
CFDataRef *attrOid, CFArrayRef *attrValues) {
if(attrNum >= numAttrs()) {
MacOSError::throwMe(errSecParam);
}
NSS_Attribute *attr = mAttrs[attrNum];
*attrOid = p12CssmDataToCf(attr->attrType);
unsigned numVals = nssArraySize((const void **)attr->attrValue);
if(numVals == 0) {
*attrValues = NULL;
return;
}
CFMutableArrayRef vals = CFArrayCreateMutable(NULL, numVals, NULL);
for(unsigned dex=0; dex<numVals; dex++) {
CFDataRef val = p12CssmDataToCf(*attr->attrValue[dex]);
CFArrayAppendValue(vals, val);
}
*attrValues = vals;
}
#pragma mark --- private methods ---
NSS_Attribute *P12BagAttrs::reallocAttrs(
size_t numNewAttrs)
{
unsigned curSize = numAttrs();
assert(numNewAttrs > curSize);
NSS_Attribute **newAttrs =
(NSS_Attribute **)p12NssNullArray((uint32)numNewAttrs, mCoder);
for(unsigned dex=0; dex<curSize; dex++) {
newAttrs[dex] = mAttrs[dex];
}
mAttrs = newAttrs;
for(unsigned dex=curSize; dex<numNewAttrs; dex++) {
mAttrs[dex] = mCoder.mallocn<NSS_Attribute>();
memset(mAttrs[dex], 0, sizeof(NSS_Attribute));
}
return mAttrs[curSize];
}
void P12BagAttrs::copyAttr(
const NSS_Attribute &src,
NSS_Attribute &dst)
{
mCoder.allocCopyItem(src.attrType, dst.attrType);
unsigned numVals = nssArraySize((const void **)src.attrValue);
dst.attrValue = (CSSM_DATA **)p12NssNullArray(numVals, mCoder);
for(unsigned dex=0; dex<numVals; dex++) {
CSSM_DATA *dstVal = mCoder.mallocn<CSSM_DATA>();
memset(dstVal, 0, sizeof(CSSM_DATA));
dst.attrValue[dex] = dstVal;
mCoder.allocCopyItem(*src.attrValue[dex], *dstVal);
}
}