Compare Revisions

The credentials to download the source code are:
 Username: svnusers
 Password: svnusers

Ignore whitespace Rev 1916 → Rev 1917

/trunk/javasrc/adapter/org/etsi/its/adapter/Management.java
27,6 → 27,8
import org.etsi.its.adapter.ports.GnPort;
import org.etsi.ttcn.tci.CharstringValue;
 
import de.fraunhofer.sit.c2x.CryptoLib;
 
/**
* This class is used to centralise test adapter configuration and execution parameters
* All settings are component specific (multiton)
411,8 → 413,9
// Extract public keys
atCertificate = certificate.toByteArray();
// System.out.println("Management.setupSecuredModeFromTaConfig: certificate=" + ByteHelper.byteArrayToString(value));
atCertificateDigest = new byte[8];
System.arraycopy(atCertificate, 3, atCertificateDigest, 0, 8);
// Compute AT certificate digest
byte[] atHash = CryptoLib.hashWithSha256(atCertificate);
atCertificateDigest = ByteHelper.extract(atHash, atHash.length - 8, 8);
// System.out.println("Management.setupSecuredModeFromTaConfig: atCertificateDigest=" + ByteHelper.byteArrayToString(atCertificateDigest));
int offset = 18;
// KeyX
/trunk/javasrc/adapter/org/etsi/its/adapter/TlsHelper.java
7,7 → 7,7
 
import java.io.ByteArrayInputStream;
 
import org.etsi.ttcn.common.ByteHelper;
import org.etsi.common.ByteHelper;
 
public class TlsHelper {
/trunk/javasrc/adapter/org/etsi/its/adapter/ports/GnPort.java
242,7 → 242,7
@Override
public boolean send(byte[] message) {
HashMap<String, Object> params = new HashMap<String, Object>();
ByteHelper.dump(">>> GnPort.send", message);
// ByteHelper.dump(">>> GnPort.send", message);
byte[] destMacAddress = ByteHelper.extract(message, message.length - 6, 6);
message = ByteHelper.extract(message, 0, message.length - 6);
250,7 → 250,7
if (management.isSecuredModeSet()) { // Secure mode disabled
message = createSecuredMessage(message);
}
ByteHelper.dump("GnPort.send", message);
// ByteHelper.dump("GnPort.send", message);
return send(message, params);
}
/trunk/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPort.java
77,7 → 77,7
public boolean send(byte[] message) {
HashMap<String, Object> params = new HashMap<String, Object>();
ByteHelper.dump("ProtocolPortLayer.send", message);
// ByteHelper.dump("ProtocolPortLayer.send", message);
return send(message, params);
}
/trunk/javasrc/certificatesio/org/etsi/certificates/CertificatesIOFactory.java
6,11 → 6,6
public class CertificatesIOFactory {
/**
* The single instance of this class.
*/
private static CertificatesIOFactory _instance = new CertificatesIOFactory();
/**
* The single instance of the class CertificatesIO.
*/
private static ICertificatesIO _certIO = new CertificatesIO();
20,7 → 15,7
* @return The single instance of this class.
*/
public static ICertificatesIO getInstance() {
return _instance._certIO;
return _certIO;
}
/**
/trunk/javasrc/certificatesio/org/etsi/certificates/Helpers.java
7,6 → 7,7
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
68,32 → 69,46
 
/**
* Recursively walk a directory tree and return a List of all Files found; the List is sorted using File.compareTo().
* @param startingDir is a valid directory, which can be read.
* @param p_startingDir The valid directory, which can be read.
* @param p_extension The file extension, in lower case
* @param p_excludedPatterns The pattern which shall be excluded, in lower case
*/
public List<File> getFileListing(File startingDir) throws FileNotFoundException {
validateDirectory(startingDir);
List<File> result = getFileListingNoSort(startingDir);
public List<File> getFileListing(File p_startingDir, final String p_extension, final String[] p_excludedPatterns) throws FileNotFoundException {
validateDirectory(p_startingDir);
List<File> result = getFileListingNoSort(p_startingDir, p_extension, p_excludedPatterns);
Collections.sort(result);
return result;
}
 
private List<File> getFileListingNoSort(File startingDir) throws FileNotFoundException {
private List<File> getFileListingNoSort(final File p_startingDir, final String p_extension, final String[] p_excludedPatterns) throws FileNotFoundException {
List<File> result = new ArrayList<File>();
File[] filesAndDirs = startingDir.listFiles();
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File p_dirName, final String p_fileName) {
String name = p_fileName.toLowerCase();
if (!p_extension.isEmpty() && !name.endsWith(p_extension)) {
return false;
}
if (p_excludedPatterns != null) {
for (String excludePattern : p_excludedPatterns) {
if (name.indexOf(excludePattern) != -1) {
return false;
}
}
}
return true;
}
};
File[] filesAndDirs = p_startingDir.listFiles(filter);
List<File> filesDirs = Arrays.asList(filesAndDirs);
for (File file : filesDirs) {
if (file.isDirectory() && ((file.getName().indexOf(".svn") != -1)
|| (file.getName().indexOf("._.DS_Store") != -1)
|| (file.getName().indexOf(".DS_Store") != -1))) { // For debug purpose only
// Skip svn files
continue;
}
result.add(file); // always add, even if directory
if (!file.isFile()) {
//must be a directory
//recursive call!
List<File> deeperList = getFileListingNoSort(file);
List<File> deeperList = getFileListingNoSort(file, p_extension, p_excludedPatterns);
result.addAll(deeperList);
}
}
/trunk/javasrc/certificatesio/org/etsi/certificates/io/CertificatesIO.java
13,65 → 13,49
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.etsi.certificates.Helpers;
import org.etsi.common.ByteHelper;
 
import de.fraunhofer.sit.c2x.CryptoLib;
 
public class CertificatesIO implements ICertificatesIO {
/**
* Regex pattern to extract signing private key
* Relative path for to extract certificates
*/
private static final String SIGNING_PRIVATE_KEY_PATTERN = "^SigningPrivate key\\s*=\\s*([A-Fa-f0-9]+)$";
private static final String CERTS_PATH = "/certs_store";
/**
* Regex pattern to extract encrypt private key
* Extension file for private keys
*/
private static final String ENCRYPT_PRIVATE_KEY_PATTERN = "^EncryptPrivate key\\s*=\\s*([A-Fa-f0-9]+)$";
private static final String KEYS_EXT = "bin";
/**
* Regex pattern to extract AA certificate
* Relative path for to extract private keys
*/
private static final String CERT_AA_PATTERN = "^AUTHORIZATION_AUTHORITY.dump\\s*=\\s*([A-Fa-f0-9]+)$";
private static final String KEYS_PATH = "/priv_keys";
/**
* Regex pattern to extract AT certificate
* Full path to access certificate files
*/
private static final String CERT_AT_PATTERN = "^AUTHORIZATION_TICKET.dump\\s*=\\s*([A-Fa-f0-9]+)$";
private String _fullPathCerts;
/**
* Regex compiler to extract signing private key
* Full path to access key files
*/
private Pattern signingPrivateKeyPattern = Pattern.compile(SIGNING_PRIVATE_KEY_PATTERN, Pattern.MULTILINE);
private String _fullPathKeys;
/**
* Regex compiler to extract encrypt private key
* Memory cache for the certificates
*/
private Pattern encryptPrivateKeyPattern = Pattern.compile(ENCRYPT_PRIVATE_KEY_PATTERN, Pattern.MULTILINE);
private Map<String, byte[]> _cachedCertificates;
/**
* Regex compiler to extract AA certificate
*/
private Pattern certAaPattern = Pattern.compile(CERT_AA_PATTERN, Pattern.MULTILINE);
private Map<String, byte[]> _cachedCertificatesDigest;
/**
* Regex compiler to extract AT certificate
*/
private Pattern certAtPattern = Pattern.compile(CERT_AT_PATTERN, Pattern.MULTILINE);
private Map<String, String> _cachedReverseCertificatesDigest;
/**
* Full path to access certificate files
*/
private String _fullPath;
/**
* Memory cache for the certificates
*/
private Map<String, byte[]> _cachedCertificates;
/**
* Memory cache for the signing private keys
*/
private Map<String, byte[]> _cachedSigningPrivateKey;
86,8 → 70,10
*/
public CertificatesIO() {
_cachedCertificates = new ConcurrentHashMap<String, byte[]>();
_cachedCertificatesDigest = new ConcurrentHashMap<String, byte[]>();
_cachedSigningPrivateKey = new ConcurrentHashMap<String, byte[]>();
_cachedEncryptPrivateKey = new ConcurrentHashMap<String, byte[]>();
_cachedReverseCertificatesDigest = new ConcurrentHashMap<String, String>();
} // End of Constructor
/**
99,31 → 85,36
@Override
public boolean loadCertificates(final String rootDirectory, final String configId) { // E.g. <rootDirectory path>, cfg01
// Initialise the memory caches
_cachedCertificates.clear();
_cachedSigningPrivateKey.clear();
_cachedEncryptPrivateKey.clear();
unloadCertificates();
// Build full path
if ((rootDirectory == null) || (rootDirectory.length() == 0)) {
_fullPath = System.getProperty("user.dir").replace("\\", "/");
_fullPathCerts = System.getProperty("user.dir").replace("\\", "/");
} else {
_fullPath = rootDirectory.replace("\\", "/");
_fullPathCerts = rootDirectory.replace("\\", "/");
}
if (!_fullPath.endsWith("/")) {
_fullPath += "/";
if (!_fullPathCerts.endsWith("/")) {
_fullPathCerts += "/";
}
if ((configId != null) && (configId.length() != 0)) {
_fullPath += configId.replace('.', '/');
_fullPathCerts += configId.replace('.', '/');
}
_fullPath = _fullPath.toLowerCase();
// Check the path
File path = new File(_fullPath);
if (!path.exists()) {
System.err.println("CertificatesIO.readCertificate: path '" + _fullPath + "' does not found");
_fullPathCerts = _fullPathCerts.toLowerCase();
_fullPathKeys = _fullPathCerts + KEYS_PATH;
_fullPathCerts += CERTS_PATH;
// Check the paths
File keysPath = new File(_fullPathKeys);
if (!keysPath.exists()) {
System.err.println("CertificatesIO.readCertificate: path '" + _fullPathKeys + "' does not found");
return false;
}
File certsPath = new File(_fullPathCerts);
if (!certsPath.exists()) {
System.err.println("CertificatesIO.readCertificate: path '" + _fullPathCerts + "' does not found");
return false;
}
return loadMemoryCache(path); // Load certificates and keys and return
return loadMemoryCache(keysPath); // Load certificates and keys and return
}
/**
132,9 → 123,13
*/
@Override
public boolean unloadCertificates() {
_fullPath = null;
_fullPathKeys = null;
_fullPathCerts = null;
_cachedCertificates.clear();
_cachedCertificatesDigest.clear();
_cachedSigningPrivateKey.clear();
_cachedEncryptPrivateKey.clear();
_cachedReverseCertificatesDigest.clear();
return true;
}
163,6 → 158,26
return false;
}
@Override
public boolean readCertificateDigest(final String certificateId, final ByteArrayOutputStream digest) {
// Sanity check
String key = certificateId + ".DIGEST";
if (!_cachedCertificatesDigest.containsKey(key)) {
System.err.println("CertificatesIO.readCertificate: key '" + key + "' not found");
return false;
}
try {
digest.write(_cachedCertificatesDigest.get(key));
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
* @desc Read the private keys for the specified certificate
* @param keysId the keys identifier
189,10 → 204,16
return false;
}
private boolean loadMemoryCache(final File path) { // E.g. <path>/ta_config_a.txt
// Retrieve the list of the files in the _fullpath
/**
* @desc Load certificates based on existing keys file, excluding xxx_at.bin files
* @param p_keysPath path for private key files
* @param p_certsPath Path for certificate files
* @return true on success, false otherwise
*/
private boolean loadMemoryCache(final File p_keysPath) { // E.g. <path>/keys, <path>/certs
// Retrieve the list of the files in the p_keysPath
try {
List<File> files = Helpers.getInstance().getFileListing(path);
List<File> files = Helpers.getInstance().getFileListing(p_keysPath, KEYS_EXT, new String[] { "_at", "_aa", /*for debug: */".svn", "._.DS_Store", ".DS_Store"});
// Create the memory cache
for (File file : files) {
addItem(file);
205,47 → 226,87
return false;
}
 
private void addItem(final File file) throws FileNotFoundException, IOException {
String key = file.getName().substring(0, file.getName().indexOf('.')).toUpperCase();
private void addItem(final File p_keysFile) throws FileNotFoundException, IOException {
// Sanity checks
if (p_keysFile.length() != 32) { // FIXME Should have both encrypt and singing keys
return;
}
// Load the keys file name
String filename = p_keysFile.getName().toLowerCase();
String keysFileName = filename.substring(0, filename.indexOf("_ca"));
File caFile = new File(_fullPathCerts + "/" + keysFileName + "_ca.crt");
File aaFile = new File(_fullPathCerts + "/" + keysFileName + "_aa.crt");
File atFile = new File(_fullPathCerts + "/" + keysFileName + "_at.crt");
String key = keysFileName.toUpperCase();
if (!_cachedCertificates.containsKey(key)) {
FileInputStream fs = new FileInputStream(file.getCanonicalPath());
byte bytes[] = new byte[(int) file.length()];
fs.read(bytes);
String content = new String(bytes);
// Open CA keys file
FileInputStream fsKeys = new FileInputStream(p_keysFile.getCanonicalPath());
// Load keys
byte bytes[] = new byte[(int) p_keysFile.length()];
fsKeys.read(bytes);
_cachedSigningPrivateKey.put(key + ".CA_PRIVATE_KEYS", ByteHelper.extract(bytes, 0, 32));
// FIXME Should have both encrypt and singing keys _cachedEncryptPrivateKey.put(key + ".PRIVATE_KEYS", ByteHelper.extract(bytes, 32, 32));
_cachedEncryptPrivateKey.put(key + ".CA_PRIVATE_KEYS", ByteHelper.extract(bytes, 0, 32));
// Close file stream
fsKeys.close();
// Open CA keys file
fsKeys = new FileInputStream(p_keysFile.getCanonicalPath().toLowerCase().replaceAll("_ca", "_at"));
// Load keys
bytes = new byte[(int) p_keysFile.length()];
fsKeys.read(bytes);
_cachedSigningPrivateKey.put(key + ".AT_PRIVATE_KEYS", ByteHelper.extract(bytes, 0, 32));
// FIXME Should have both encrypt and singing keys _cachedEncryptPrivateKey.put(key + ".PRIVATE_KEYS", ByteHelper.extract(bytes, 32, 32));
_cachedEncryptPrivateKey.put(key + ".AT_PRIVATE_KEYS", ByteHelper.extract(bytes, 0, 32));
// Close file stream
fsKeys.close();
// Extract SigningPrivateKey. Key identifier is key.PRIVATE_KEYS
// E.g. SigningPrivate key=68E45C8BBE0ABFA80188E62D082D7A1E5FD4D637D99A5826781280F3865B5819
Matcher matcher = signingPrivateKeyPattern.matcher(content);
if (matcher.find()) {
// System.out.println("CertificatesIO.addItem: Add key '" + key + ".PRIVATE_KEYS" + "'");
_cachedSigningPrivateKey.put(key + ".PRIVATE_KEYS", ByteHelper.hexStringToByteArray(matcher.group(1)));
}
// Extract EncryptPrivate. Key identifier is key.PRIVATE_KEYS
// E.g. EncryptPrivate key=00B65233550BE5A9866CF871D7712691CC47532A08C620D20579FB02BEFA3D1C5F
matcher = encryptPrivateKeyPattern.matcher(content);
if (matcher.find()) {
// System.out.println("CertificatesIO.addItem: Add key '" + key + ".PRIVATE_KEYS" + "'");
_cachedEncryptPrivateKey.put(key + ".PRIVATE_KEYS", ByteHelper.hexStringToByteArray(matcher.group(1)));
}
// Open CA certificate
FileInputStream fsCaFile = new FileInputStream(caFile.getCanonicalPath());
bytes = new byte[(int) caFile.length()];
fsCaFile.read(bytes);
_cachedCertificates.put(key + ".CA_CERT", bytes);
// Close file streams
fsCaFile.close();
// Extract AUTHORIZATION_AUTHORITY.dump. Key identifier is key.AA_CERT
// E.g. AUTHORIZATION_AUTHORITY.dump=02015791FDC6CE82402F0210455453495F506C7567746573745F414180910000040E5F7F47D7A165E2DC403F1E8BAA14E6FF04ADE282CB22212056444CE0F193B01493338B6A8A5D36B2BE9CD3D1F5C708862BCD4539F9D99A0D9F7347066A92C001010004402A571AF5293651B3E2A931CEB1009805EB92E44288D08510E67BA629F14D61402A571AF5293651B3E2A931CEB1009805EB92E44288D08510E67BA629F14D6102202006C04080C040812401146757031A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000A3EECD601A7D17D4C1EB4B8205EEFAE45E170872D49741941B5C9AEDEAA76E38938A67F98DCD46D390B9CF4C16AD324B9E6520565994790029A841E4C820BE4D
matcher = certAaPattern.matcher(content);
if (matcher.find()) {
// System.out.println("CertificatesIO.addItem: Add key '" + key + ".AA_CERT" + "'");
_cachedCertificates.put(key + ".AA_CERT", ByteHelper.hexStringToByteArray(matcher.group(1)));
}
// Open AA certificate
FileInputStream fsAaFile = new FileInputStream(aaFile.getCanonicalPath());
bytes = new byte[(int) aaFile.length()];
fsAaFile.read(bytes);
_cachedCertificates.put(key + ".AA_CERT", bytes);
// Close file streams
fsAaFile.close();
// Extract AUTHORIZATION_TICKET.dump. Key identifier is key.AT_CERT
// E.g. AUTHORIZATION_TICKET.dump=0201CDF3567352CD8B4401008095000004DCBD7FBD344A653D42420350D3CB84E68C1E618ACC16FF4BA31D9D2913530A1ADED6F691D23476E779CCA54C63327F28E9E943929CF5C459DDA01E459279CAA0010100041D2EE0E362BF2798C5148BB198B2EB3718CB0B8714580A70A7161A5550D71F364FF1D5098A18E2B9CE142A17B5558A9E54438823D146CC24A372E7CE1761AF100220210AC040800100C0408101002401146757031A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000AE35B36EA820B183AD0AD732656E2606A8C373C95DFA580FF4C049C66FEFD76F0B558C16932B4DC2BA0D52966AC3D56AC20E606DEDE63B625B4B80FDE1269335
matcher = certAtPattern.matcher(content);
if (matcher.find()) {
// System.out.println("CertificatesIO.addItem: Add key '" + key + ".AT_CERT" + "'");
_cachedCertificates.put(key + ".AT_CERT", ByteHelper.hexStringToByteArray(matcher.group(1)));
}
// Open AT certificate
FileInputStream fsAtFile = new FileInputStream(atFile.getCanonicalPath());
bytes = new byte[(int) atFile.length()];
fsAtFile.read(bytes);
_cachedCertificates.put(key + ".AT_CERT", bytes);
byte[] digest = calculateDigestFromCertificate(bytes);
_cachedCertificatesDigest.put(key + ".AT_CERT.DIGEST", digest);
_cachedReverseCertificatesDigest.put(ByteHelper.byteArrayToString(digest), key + ".AT_CERT.DIGEST");
// Close file streams
fsAtFile.close();
} // else, ignore it
}
@Override
public String getKeyIdFromHashedId8(byte[] p_hashedId8ToBeUsed) {
String key = ByteHelper.byteArrayToString(p_hashedId8ToBeUsed);
if (!_cachedReverseCertificatesDigest.containsKey(key)) {
return null;
}
return _cachedReverseCertificatesDigest.get(key).substring(0, key.length() - 7/*.DIGEST*/);
}
private byte[] calculateDigestFromCertificate(final byte[] p_toBeHashedData) {
byte[] hash = CryptoLib.hashWithSha256(p_toBeHashedData);
return ByteHelper.extract(hash, hash.length - 8, 8);
}
} // End of class CertificatesIO
/trunk/javasrc/certificatesio/org/etsi/certificates/io/ICertificatesIO.java
37,6 → 37,14
boolean readCertificate(final String certificateId, final ByteArrayOutputStream certificate);
/**
* @desc Read the specified certificate digest
* @param certificateId the certificate identifier
* @param digest the expected digest
* @return true on success, false otherwise
*/
boolean readCertificateDigest(final String certificateId, final ByteArrayOutputStream digest);
/**
* @desc Read the private keys for the specified certificate
* @param keysId the keys identifier
* @param signingPrivateKey the signing private key
45,4 → 53,11
*/
boolean readPrivateKeys(final String keysName, final ByteArrayOutputStream signingPrivateKey, final ByteArrayOutputStream encryptPrivateKey);
/**
* @desc Retrieve the key identifier associated to the Digest value
* @param p_hashedId8ToBeUsed the Digest value
* @return The key identifier
*/
String getKeyIdFromHashedId8(final byte[] p_hashedId8ToBeUsed);
} // End of interface ICertificatesIO
/trunk/javasrc/codec/org/etsi/ttcn/codec/MainCodec.java
38,8 → 38,8
 
@Override
public Value decode(CodecBuffer buf, Type decodingHypothesis) {
System.out.println(">>> MainCodec.decode: " + decodingHypothesis.getName());
ByteHelper.dump(">>> MainCodec.decode: ", buf.getBytes());
// System.out.println(">>> MainCodec.decode: " + decodingHypothesis.getName());
// ByteHelper.dump(">>> MainCodec.decode: ", buf.getBytes());
CodecFactory cf = CodecFactory.getInstance();
TciCDProvided extCodec = cf.getExternalCodec(decodingHypothesis.getTypeEncoding());
61,10 → 61,10
codec.preDecode(buf, decodingHypothesis);
// TODO To be removed, for debug purpose only
Value decValue = codec.decode(buf, decodingHypothesis);
System.out.println("<<< MainCodec.decode: " + decValue);
return decValue;
// return codec.decode(buf, decodingHypothesis);
// Value decValue = codec.decode(buf, decodingHypothesis);
// System.out.println("<<< MainCodec.decode: " + decValue);
// return decValue;
return codec.decode(buf, decodingHypothesis);
}
}
 
90,7 → 90,7
buf = preBuf;
}
ByteHelper.dump("<<< MainCodec.encode: ", buf.getBytes());
// ByteHelper.dump("<<< MainCodec.encode: ", buf.getBytes());
return buf;
}
}
/trunk/javasrc/codec/org/etsi/ttcn/codec/generic/Float.java
26,7 → 26,7
FloatValue fv = mainCodec.getTciCDRequired().getFloat();
fv.setFloat(ByteHelper.byteArrayToFloat(buf.readBits(java.lang.Float.SIZE)));
System.out.println("<<< Float.decode: " + fv.getFloat());
// System.out.println("<<< Float.decode: " + fv.getFloat());
return fv;
}
/trunk/javasrc/codec/org/etsi/ttcn/codec/its/security/Plugin.java
113,6 → 113,7
cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "HeaderFieldContainer.its_aid", IntX.class);
cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "ValidityRestrictionContainer.end_validity", Time32.class);
cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "SignerInfoContainer.certificates", RecordOf.class);
cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "GeographicRegionContainer.rectangular_region", RecordOf.class);
cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "GeographicRegionContainer.polygonal_region", RecordOf.class);
cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HeaderFieldContainer.digests", RecordOf.class);
/trunk/javasrc/codec/org/etsi/ttcn/codec/its/security/RecordOf.java
24,6 → 24,7
// System.out.println(">>> security.RecordOf.decode: " + decodingHypothesis.getName());
int len = (int) TlsHelper.getInstance().tls2size(buf);// buf.readBytes(1)[0]; // Get number of items into the RecordOf
// System.out.println("security.RecordOf.decode: length=" + len);
if (len == 0) {
RecordOfValue rov = (RecordOfValue)decodingHypothesis.newInstance();
rov.setLength(0);
/trunk/tools/itscertgen/certgen.c
0,0 → 1,1118
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "cxml/cxml.h"
#include "cshared/copts.h"
#include "cshared/cserialize.h"
#include "cshared/cstr.h"
 
#include "ecc_api.h"
#include "mkgmtime.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include <time.h>
#include <math.h>
 
//#define DEBUG_BOOKMARKS
#define MAX_BOOKMARKS 16
 
typedef struct bookmark_t bookmark_t;
struct bookmark_t {
bookmark_t * prev;
char * ptr;
};
 
typedef struct cert_cxml_handler_t
{
cxml_handler_t h;
unsigned int subject_type;
int signer_type;
const char * signer;
int vr_type;
int sa_type;
void * verificationKey;
void * encryptionKey;
 
 
char * buf;
char * ptr;
const char * end;
 
char * bookmarks[MAX_BOOKMARKS];
int bidx;
 
unsigned int nTmpValue;
void * key;
}cert_cxml_handler_t;
 
static void bookmark_position(cert_cxml_handler_t * const h, const cxml_tag_t * tag)
{
if (h->bidx >= MAX_BOOKMARKS){
fprintf(stderr, "FATAL: Profile is tooooooo complicated!!!\n");
exit(-1);
}
h->bookmarks[h->bidx] = h->ptr;
h->bidx++;
h->ptr++;
#ifdef DEBUG_BOOKMARKS
printf("BOOKMARK 0x%08X (%s)\n", (unsigned int)h->ptr, tag->name);
#endif
}
 
static int apply_bookmark_size(cert_cxml_handler_t * const h, const cxml_tag_t * tag)
{
int size, bcount;
char * psize;
if (h->bidx == 0){
fprintf(stderr, "FATAL: Inconsistent bookmarks!!!\n");
exit(-1);
}
psize = h->bookmarks[--h->bidx];
size = h->ptr - psize - 1;
#ifdef DEBUG_BOOKMARKS
printf("APPLY 0x%08X [%d] (%s)\n", (unsigned int)h->ptr, size, tag->name);
#endif
bcount = cintx_bytecount(size);
if (bcount == 1){
*(unsigned char*)psize = size;
size = 0;
}
else{
memmove(psize + bcount, psize + 1, h->ptr - psize - 1);
h->ptr += bcount - 1;
size = cintx_write(size, &psize, psize + bcount, NULL);
}
return size; // size is overridden to be 0 or -1
}
 
static int attribute_public_key_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_eccpoint_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_assurance_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_aid_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_ssp_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int attribute_ssp_text (cxml_handler_t* const h, char * const text, int length);
 
static const cxml_taghandler_t h_attribute[] = {
{"public-key", attribute_public_key_tag, NULL, NULL },
{"public_key", attribute_public_key_tag, NULL, NULL },
{"eccpoint", attribute_eccpoint_tag, NULL, NULL },
{"assurance", attribute_assurance_tag, NULL, NULL },
{"aid", attribute_aid_tag, NULL, NULL },
{"ssp", attribute_ssp_tag, attribute_ssp_text, NULL },
{NULL}
};
 
static int subject_attribute_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_subject[] = {
{"attribute", subject_attribute_tag, NULL, h_attribute},
{NULL}
};
 
static int location_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_location_list [] = {
{"location", location_tag, NULL, NULL },
{NULL}
};
 
static int region_none_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_circle_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_rectangle_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_polygon_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int region_id_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_restriction[] = {
{"none", region_none_tag, NULL, NULL },
{"circle", region_circle_tag, NULL, NULL },
{"rectangle", region_rectangle_tag, NULL, h_location_list },
{"polygon", region_polygon_tag, NULL, h_location_list },
{"id", region_id_tag, NULL, NULL },
{NULL}
};
 
static int validity_restriction_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_validity[] = {
{"restriction", validity_restriction_tag, NULL, h_restriction },
{NULL}
};
static int certificate_version_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_version_text(cxml_handler_t* const h, char * const text, int length);
static int certificate_signer_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_signer_text(cxml_handler_t* const h, char * const text, int length);
static int certificate_subject_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_validity_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static int certificate_signature_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_certificate[] = {
{"version", certificate_version_tag, certificate_version_text, NULL },
{"signer", certificate_signer_tag, certificate_signer_text, NULL },
{"subject", certificate_subject_tag, NULL, h_subject },
{"validity", certificate_validity_tag, NULL, h_validity },
{"signature", certificate_signature_tag, NULL, h_validity },
{NULL}
};
 
static int root_certificate_tag (cxml_handler_t* const h, cxml_tag_t * const tag);
static const cxml_taghandler_t h_root[] = {
{"certificate", root_certificate_tag, NULL, h_certificate },
{NULL}
};
 
static int _Begin_Tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int _End_Tag(cxml_handler_t* const h, cxml_tag_t * const tag);
static int _Text(cxml_handler_t* const h, char * const text, int length);
 
 
static cxml_handler_class Class = {
sizeof(cert_cxml_handler_t),
NULL, NULL,
_Begin_Tag, _End_Tag,
_Text
};
 
#define STR2ENUM(N,V) _str_2_enum(N, sizeof(N)/sizeof(N[0]), V)
 
static int _str_2_enum(const char ** values, size_t size, const char * v)
{
while (*v && isspace(*v))v++;
if (*v){
size_t i;
for (i = 0; i<size; i++){
if (values[i] && 0 == strcmp(values[i], v)) {
return i;
}
}
if (isdigit(*v)){
return strtoul(v, NULL, 0);
}
}
return -1;
}
 
 
static unsigned int _convert_time(const char * v);
 
static const char *_outPath = ".";
static const char *_searchPath = NULL;
static const char *_certName = NULL;
static char *_profileName = NULL;
static const char *_signerName = NULL;
static unsigned int _defaultTime = 0;
static ecc_format _outFormat = 0;
static const char * _outExtensions[] = {
"bin", "hex", "pem"
};
static const char * _verificationKey = NULL;
static const char * _decriptionKey = NULL;
static const char * _keyPath = NULL;
static int _reuseKeys = 0;
 
static int _time_option(const copt_t * opt, const char * option, const copt_value_t * value)
{
_defaultTime = _convert_time(value->v_str);
return (_defaultTime == (unsigned int)-1) ? -1 : 0;
}
static int _out_option(const copt_t * opt, const char * option, const copt_value_t * value)
{
_outFormat = STR2ENUM(_outExtensions, opt->lopt);
if (_outFormat >= 0){
return 0;
}
return -1;
}
 
static copt_t options [] = {
{ "h?", "help", COPT_HELP, NULL, "Print this help page" },
{ "o", "out", COPT_STR, (void*)&_outPath, "Output path [current dir by default]" },
{ "S", "certs", COPT_STR, (void*)&_searchPath, "Certificates search path [Output path by default]" },
{ "K", "keys", COPT_STR, (void*)&_keyPath, "Private key storage path [Output path by default]" },
{ "R", "reuse", COPT_BOOL, (void*)&_reuseKeys, "Reuse existing key pair [regenerate by default]" },
{ "b", "bin", (COPT_BOOL | COPT_CALLBACK), (void*)&_out_option, "Binary output format [default]" },
{ "p", "pem", (COPT_BOOL | COPT_CALLBACK), (void*)&_out_option, "PEM output format" },
{ "x", "hex", (COPT_BOOL | COPT_CALLBACK), (void*)&_out_option, "Hexadecimal output format" },
{ "n", "name", COPT_STR, (void*)&_certName, "Certificate name (take from profile by default)" },
{ "v", "vkey", COPT_STR, (void*)&_verificationKey, "Verification public key (generate key pair by default)" },
{ "e", "ekey", COPT_STR, (void*)&_decriptionKey, "Decription public key (generate key pair if neccessary)" },
{ "s", "signer", COPT_STR, (void*)&_signerName, "Signer certificate name [take from profile by default]" },
{ "r", "reftime", COPT_STR | COPT_CALLBACK, (void*)&_time_option, "Reference UTC time point (YYY-DD-MM) [current date]" },
// { "c", "chain", COPT_BOOL , &_createChain, "Produce a text file for ITS Test Suite" },
{ NULL, NULL, COPT_END, NULL, NULL }
};
 
int main(int argc, char ** argv)
{
FILE *f;
 
cert_cxml_handler_t * h = cxml_st_handler_new(&Class, h_root);
h->vr_type = -1;
h->sa_type = -1;
argc = coptions(argc, argv, COPT_NOCONFIG | COPT_HELP_NOVALUES , options);
 
if(argc < 2){
if(argc<0 && (0-argc)<((sizeof(options)/sizeof(options[0]))-1)){
printf("Unknown option %s\n", argv[0-argc]);
}
const char * a = strrchr(argv[0], '/');
if (a == NULL) a = argv[0];
coptions_help(stdout, a, COPT_HELP_NOVALUES, options, "<profile> [signer]");
return -1;
}
 
if (_searchPath == NULL) _searchPath = _outPath;
if (_keyPath == NULL) _keyPath = _outPath;
 
if(argc > 2){
// set signer certificate file name
_signerName = argv[2];
}
 
f = fopen(argv[1], "r");
if(f == NULL){
fprintf(stderr, "%s: Certificate profile not found\n", argv[1]);
return -1;
}else{
if(ecc_api_init()){
return -1;
}
 
_profileName = cstrdup(cstrlastpathelement(argv[1]));
if(_profileName){
char * p = strrchr(_profileName, '.');
if(p) *p = 0;
}
 
if(0 != cxml_handler_parse_stream(&h->h, f)){
fprintf(stderr, "%s Profile parsing error\n", argv[1]);
return -1;
}
fclose(f);
 
ecc_api_done();
}
return 0;
}
 
static int root_certificate_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
if(_certName == NULL){
_certName = cxml_tag_attr_value(tag, "name");
if(_certName == NULL){
_certName = _profileName;
}
}
h->ptr = h->buf = malloc(4096);
h->end = h->buf + 4096;
}else{
FILE * f;
char * path = h->ptr;
char * end = cvstrncpy(path, h->end-path, _outPath, "/", _certName, ".crt", NULL);
f = fopen(path, "wb");
if (!f){
fprintf(stderr, "ERROR: Certificate write failed to '%s'\n", path);
}else{
if (_outFormat == 1){ // hex format
const char * p = h->buf;
for (; p < h->ptr; p++){
fprintf(f, "%02X", (unsigned int)*p);
}
}else{
fwrite(h->buf, 1, h->ptr - h->buf, f);
}
fclose(f);
}
if (h->verificationKey){
if (_verificationKey == NULL && _reuseKeys == 0){
cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".v.prv.", _outExtensions[_outFormat], NULL);
ecc_api_key_private_save(h->verificationKey, path, _outFormat);
cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".v.pub.", _outExtensions[_outFormat], NULL);
ecc_api_key_public_save(h->verificationKey, path, _outFormat);
}
}
if (h->encryptionKey){
if (_decriptionKey == NULL && _reuseKeys == 0){
cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".e.prv.", _outExtensions[_outFormat], NULL);
ecc_api_key_private_save(h->encryptionKey, path, _outFormat);
cvstrncpy(path, h->end - path, _keyPath, "/", _certName, ".e.pub.", _outExtensions[_outFormat], NULL);
ecc_api_key_public_save(h->encryptionKey, path, _outFormat);
}
}
free(h->buf);
}
return 0;
}
 
static int certificate_version_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
h->nTmpValue = 2;
const char * v = cxml_tag_attr_value(tag, "version");
if(v == NULL)v = cxml_tag_attr_value(tag, "value");
if(v){
while(isspace(*v))v++;
h->nTmpValue = strtoul(v, NULL, 0);
}
}else{
cint8_write(h->nTmpValue, &h->ptr, h->end, &rc);
}
return rc;
}
 
static int certificate_version_text(cxml_handler_t* const _h, char * const text, int length)
{
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if(text){
const char * p = text;
while(*p && isspace(*p))p++;
if(*p) h->nTmpValue = strtoul(p, NULL, 0);
}
return 0;
}
 
static const char * _signer_types [] = {
"self",
"digest",
"certificate",
"chain",
"other",
};
 
static int certificate_signer_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
// write signer info
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
h->signer_type = 1; // digest by default
const char * v = cxml_tag_attr_value(tag, "type");
if(v){
h->signer_type = STR2ENUM(_signer_types, v);
if(h->signer_type <0){
fprintf(stderr, "%s: Unknown signer type\n", v);
return -1;
}
}
cint8_write(h->signer_type, &h->ptr, h->end, &rc);
 
if (h->signer_type > 0){
if (_signerName){
h->signer = _signerName;
}
else{
v = cxml_tag_attr_value(tag, "name");
if (v == NULL){
fprintf(stderr, "%s: Signer name shall be provided\n", v);
return -1;
}
h->signer = v;
}
}
}else{
// write signer info
if (h->signer_type > 0){
if (h->signer_type > 2){
fprintf(stderr, "%d: signer method unsupported\n", h->signer_type);
rc = -1;
}
else{
// load signer certificate
int plen = strlen(_searchPath) + strlen(h->signer);
char * path = malloc(plen + 16);
char * end = cvstrncpy(path, plen + 16, _searchPath, "/", h->signer, ".crt", NULL);
end = cstrnload(h->ptr, h->end - h->ptr, path);
if (end == NULL) {
fprintf(stderr, "%s: signer certificate not found\n", h->signer);
rc = -1;
}
else{
if (h->signer_type == 1){ // digest
char hash[sha256_hash_size];
// change eccpoint type of the signature to x_coordinate_only(0)
// to follow canonical encoding
end[-65] = 0;
sha256_calculate(hash, h->ptr, end - h->ptr);
cbuf_write(&hash[sha256_hash_size - 8], 8, &h->ptr, h->end, &rc);
}
else {// certificate
h->ptr = end;
}
}
}
}
}
return rc;
}
 
static int certificate_signer_text(cxml_handler_t* const h, char * const text, int length)
{ return 0;}
 
static const char * _subject_type [] = {
"EC", "AT", "AA", "EA", "ROOT", "CRL"
};
 
typedef struct list_pointer_t
{
unsigned char * ptr;
unsigned char cnt;
}list_pointer_t;
 
static int certificate_subject_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
// write signer info
if (cxml_tag_is_open(tag)){
int len;
const char * v = cxml_tag_attr_value(tag, "type");
if(v == NULL){
fprintf(stderr, "Subject type must be set in Certificate profile\n");
return -1;
}
h->subject_type = STR2ENUM(_subject_type, v);
if(h->subject_type < 0) {
fprintf(stderr, "%s: Unknown subject type\n", v);
return -1;
}
cint8_write(h->subject_type, &h->ptr, h->end, &rc);
v = cxml_tag_attr_value(tag, "name");
len = cstrlen(v);
if(0 == cintx_write(len, &h->ptr, h->end, &rc) && len > 0){
cbuf_write(v, len, &h->ptr, h->end, &rc);
}
bookmark_position(h, tag);
}else{
apply_bookmark_size(h, tag);
}
return rc;
}
 
static const char * _subject_attribute_types[] = {
[0] = "verification_key",
[1] = "encryption_key",
[2] = "assurance_level",
[3] = "reconstruction_value",
[32] = "its_aid_list",
[33] = "its_aid_ssp_list"
};
 
static int subject_attribute_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
const char * v = cxml_tag_attr_value(tag, "type");
int atype;
if(v == NULL){
fprintf(stderr, "Attribute type must be set\n");
return -1;
}
atype = STR2ENUM(_subject_attribute_types, v);
if(atype < 0) {
fprintf(stderr, "%s: Unknown attribute type\n", v);
return -1;
}
cint8_write(atype, &h->ptr, h->end, &rc);
h->sa_type = atype;
 
const char * keyPath = _verificationKey;
switch (h->sa_type){
case 1: // encryption_key
keyPath = _decriptionKey;
case 0: //verificationKey
if (keyPath){
h->key = ecc_api_key_public_load(keyPath);
if (h->key == NULL){
fprintf(stderr, "%s: Can't load public key\n", keyPath);
return -1;
}
}
else if (_reuseKeys){
cvstrncpy(h->ptr, h->end - h->ptr, _keyPath, "/", _certName,
".", h->sa_type ? "e" : "v", ".prv.", _outExtensions[_outFormat], NULL);
h->key = ecc_api_key_private_load(h->ptr);
if (h->key == NULL){
_reuseKeys = 0;
}
}
break;
case 32: //its_aid_list
case 33: //its_aid_ssp_list
bookmark_position(h, tag);
break;
};
}else{
switch(h->sa_type){
case 0: // verification_key
h->verificationKey = h->key;
h->key = NULL;
break;
case 1: // encryption_key
h->encryptionKey = h->key;
h->key = NULL;
break;
case 32: //its_aid_list
case 33: //its_aid_ssp_list
apply_bookmark_size(h, tag);
break;
}
if(h->key){
ecc_api_key_free(h->key);
}
h->sa_type = -1;
}
return rc;
}
 
static const char * _pk_algorithms[] = {
[0] = "ecdsa_nistp256_with_sha256",
[1] = "ecies_nistp256",
};
 
static const char * _sym_algorithms[] = {
[0] = "aes_128_ccm",
};
static const char * _point_types [] = {
[0] = "x_coordinate_only",
[1] = NULL,
[2] = "compressed",
[3] = NULL,
[4] = "uncompressed"
};
 
static int attribute_public_key_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
int alg = 0, sym_alg = 0;
void * key = h->key;
const char * v = cxml_tag_attr_value(tag, "algorithm");
if(v) {
alg = STR2ENUM(_pk_algorithms, v);
if(alg<0){
fprintf(stderr, "%s: Unknown public key algorithm\n", v);
return -1;
}
}
cint8_write(alg, &h->ptr, h->end, &rc);
switch(alg){
case 1:
v = cxml_tag_attr_value(tag, "sym_alg");
if(v){
sym_alg = STR2ENUM(_sym_algorithms, v);
if(sym_alg<0){
fprintf(stderr, "%s: Unknown symmetric algorithm\n", v);
return -1;
}
}
cint8_write(sym_alg, &h->ptr, h->end, &rc);
case 0:
// generate private and public key pair
if (key == NULL){
key = ecc_api_key_gen(alg, sym_alg);
}
if(key){
int pointtype = 0;
char x[32], y[32];
v = cxml_tag_attr_value(tag, "point-type");
if(v){
pointtype = STR2ENUM(_point_types, v);
if(pointtype < 0){
fprintf(stderr, "%s: Unknown point type\n", v);
return -1;
}
}
rc = ecc_api_key_public(key, &x[0], &y[0]);
if(rc >= 0){
if(pointtype == 2) pointtype |= (y[31]&1);
cint8_write(pointtype, &h->ptr, h->end, &rc);
if(rc==0)cbuf_write(&x[0], 32, &h->ptr, h->end, &rc);
if(rc==0 && pointtype == 4){
cbuf_write(&y[0], 32, &h->ptr, h->end, &rc);
}
}
h->key = key;
}
}
}
return rc;
}
 
static int attribute_eccpoint_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
// cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if(0 == (tag->type & CXML_TAG_OPEN)){
}else{
}
return rc;
}
 
static int attribute_assurance_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
uint8_t assurance = 0;
const char * v = cxml_tag_attr_value(tag, "level");
if(v){
while(*v && isspace(*v))v++;
if(*v){
long n = strtol(v, NULL, 0);
if(n<0 || n > 7){
fprintf(stderr, "%s: Invalid assurance level\n", v);
return -1;
}
assurance |= n<<5;
}
}
v = cxml_tag_attr_value(tag, "confidence");
if(v){
while(*v && isspace(*v))v++;
if(*v){
long n = strtol(v, NULL, 0);
if(n<0 || n > 3){
fprintf(stderr, "%s: Invalid assurance confidence\n", v);
return -1;
}
assurance |= n;
}
}
cint8_write(assurance, &h->ptr, h->end, &rc);
}
return rc;
}
 
static int attribute_aid_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if(0 == (tag->type & CXML_TAG_OPEN)){
const char * v = cxml_tag_attr_value(tag, "value");
if(NULL == v)v = cxml_tag_attr_value(tag, "aid");
if(NULL == v){
fprintf(stderr, "WARNING: Value required for AID tag. Item was skiped.\n");
}else{
uint32_t n;
while(isspace(*v))v++;
if(!isdigit(*v)){
fprintf(stderr, "ERROR: Invalid AID '%s'\n", v);
rc = -1;
}else{
n = strtoul(v, NULL, 0);
cintx_write(n, &h->ptr, h->end, &rc);
}
}
}
return rc;
}
 
static int attribute_ssp_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
uint32_t n;
const char * v = cxml_tag_attr_value(tag, "aid");
if(NULL == v){
fprintf(stderr, "ERROR: AID shall be supplied for SSP.\n");
return -1;
}
while(isspace(*v))v++;
if(!isdigit(*v)){
fprintf(stderr, "ERROR: Invalid AID '%s' in SSP\n", v);
return -1;
}
n = strtoul(v, NULL, 0);
cintx_write(n, &h->ptr, h->end, &rc);
bookmark_position(h, tag);
}else{
// write ssp buffer data
apply_bookmark_size(h, tag);
}
return rc;
}
 
static int attribute_ssp_text(cxml_handler_t* const _h, char * const text, int length)
{
int rc=0;
if(text && length){
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
rc = cbuf_write(text, length, &h->ptr, h->end, NULL);
}
return rc;
}
 
static int certificate_validity_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
bookmark_position(h, tag);
rc = 0;
}else{
rc = apply_bookmark_size(h, tag);
}
return rc;
}
 
static unsigned int _convert_time(const char * v)
{
unsigned int ret;
char * e;
struct tm tm;
// can me a difference of the predefined point in time
if(*v == '-' || *v == '+'){
const char * p;
if(_defaultTime == 0){
fprintf(stderr, "Default time must be set\n");
return 0;
}
p = v+1;
ret = 0;
for(;;){
unsigned int n;
n = strtoul(p, &e, 10);
if(n == ULONG_MAX) break;
switch(*e){
case 'd': n *= 24;
case 'h': n *= 60;
case 'm': n *= 60;
case 's': e++;
}
ret += n;
if(isdigit(*e)){
p = e;
continue;
}
break;
}
if(*v == '-'){
ret = _defaultTime - ret;
}else{
ret = _defaultTime + ret;
}
return ret;
}
// next try load as integer seconds since epoch
ret = strtoul(v, &e, 0);
if(ret == ULONG_MAX || *e){
ret = 0;
//next try to convert ISO text representation
memset(&tm, 0, sizeof(tm));
if (3 == sscanf(v, "%d-%d-%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday)){
ret = (unsigned int)mktaitime(&tm);
if (ret == (time_t)-1){
fprintf(stderr, "%s: Date format specification error. Use YYY-MM-DD\n", v);
ret = 0;
}
}
}
return ret;
}
 
static int validity_restriction_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
int vr_type = -1;
int nTime;
const char * v = cxml_tag_attr_value(tag, "type");
const char *start, *end, *duration;
if(NULL == v){
fprintf(stderr, "ERROR: Restriction shall have a type.\n");
return -1;
}
while(isspace(*v))v++;
if(0 == strcmp("time", v)){
start = cxml_tag_attr_value(tag, "start");
end = cxml_tag_attr_value(tag, "end");
duration = cxml_tag_attr_value(tag, "duration");
if(end && *end){
vr_type = (start && *start) ? 1 : 0;
}else if(start && *start && duration && *duration){
vr_type = 2;
}else{
fprintf(stderr, "ERROR: Either end or start and duration shall be specified for time restriction.\n");
return -1;
}
}else if(0 == strcmp("region", v)){
vr_type = 3;
}else if(isdigit(*v)){
vr_type=strtoul(v, NULL,0);
}else{
fprintf(stderr, "%s: Unknown validity restriction type.\n", v);
return -1;
}
h->vr_type = vr_type;
cint8_write(vr_type, &h->ptr, h->end, &rc);
// save time restrictions
switch(vr_type){
case 1: /* time_start_and_end */
nTime = _convert_time(start);
cint32_write(nTime, &h->ptr, h->end, &rc);
case 0: /* time_end */
nTime = _convert_time(end);
cint32_write(nTime, &h->ptr, h->end, &rc);
break;
case 2: /* time_start_and_duration */
nTime = _convert_time(start);
cint32_write(nTime, &h->ptr, h->end, &rc);
nTime = _convert_time(duration);
cint32_write(nTime, &h->ptr, h->end, &rc);
break;
case 3: /* region */
break;
default: // opaque
bookmark_position(h, tag); // for opaque data
}
}else{
if(h->vr_type > 3){
apply_bookmark_size(h, tag);
}
h->vr_type = -1;
}
return 0;
}
static int region_none_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
if (cxml_tag_is_open(tag)){
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
return cint8_write(0, &h->ptr, h->end, NULL);
}
return 0;
}
 
static int region_circle_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
//region type
if(0 == cint8_write(1, &h->ptr, h->end, NULL)){
//latitude and longitude
rc = location_tag (_h, tag);
if(0 == rc){
//radius
uint32_t n;
const char * v = cxml_tag_attr_value(tag, "radius");
if(NULL == v){
fprintf(stderr, "ERROR: radius shall be specified for circle.\n");
return -1;
}
n = strtoul(v, NULL, 0);
if(n > 0xFFFF){
fprintf(stderr, "ERROR: %ul: radius is too big.\n", n);
return -1;
}
cint16_write(n, &h->ptr, h->end, &rc);
}
}
}
return rc;
}
 
static int region_rectangle_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
// region type
rc = cint8_write(2, &h->ptr, h->end, NULL);
if(0 == rc){
bookmark_position(h, tag);
}
}else{
rc = apply_bookmark_size(h, tag);
}
return rc;
}
 
static int region_polygon_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
// region type
rc = cint8_write(3, &h->ptr, h->end, NULL);
if(0 == rc){
bookmark_position(h, tag);
}
}else{
rc = apply_bookmark_size(h, tag);
}
return rc;
}
 
static int location_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
if (cxml_tag_is_open(tag)){
int32_t lat, lon;
long double d;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
const char * v = cxml_tag_attr_value(tag, "latitude");
if(v == NULL){
fprintf(stderr, "ERROR: Latitude shall be specified for location.\n");
return -1;
}
d = strtold(v, NULL);
if (d <= 90.0 && d >= -90.0) d *= 10000000.0; // degree
lat = (int32_t)floorl(d);
 
v = cxml_tag_attr_value(tag, "longitude");
if(v == NULL){
fprintf(stderr, "ERROR: Longitude shall be specified for location.\n");
return -1;
}
d = strtold(v, NULL);
if (d <= 180.0 && d >= -180.0) d *= 10000000.0; // degree
lon = (int32_t)floorl(d);
 
cint32_write(lat, &h->ptr, h->end, &rc);
cint32_write(lon, &h->ptr, h->end, &rc);
}
return rc;
}
 
static const char * _id_dictionaries[] = {
"iso_3166_1",
"un_stats",
};
 
static int region_id_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
int value = 0;
unsigned int uvalue = 0;
const char * v;
 
// region dictionary. use 0 by default
v = cxml_tag_attr_value(tag, "dictionary");
if(v == NULL)v = cxml_tag_attr_value(tag, "dict");
if(v){
value = STR2ENUM(_id_dictionaries, v);
if(value<0){
fprintf(stderr, "%s: Unknown dictionary type\n", v);
return -1;
}
}
if(cint8_write(value, &h->ptr, h->end, NULL)){
return -1;
}
v = cxml_tag_attr_value(tag, "id");
if(v == NULL){
fprintf(stderr, "ERROR: Region identifier must be set\n");
return -1;
}
while(isspace(*v))v++;
uvalue = strtoul(v, NULL, 0);
if(uvalue > 0xFFFF){
fprintf(stderr, "%s: Invalid region identifier\n", v);
return -1;
}
if(cint16_write(uvalue, &h->ptr, h->end, NULL)){
return -1;
}
uvalue = 0;
v = cxml_tag_attr_value(tag, "local");
if(v){
while(isspace(*v))v++;
uvalue = strtoul(v, NULL, 0);
if(!isdigit(*v) || uvalue > 0xFFFF){
fprintf(stderr, "%s: Invalid region identifier\n", v);
return -1;
}
}
cintx_write(uvalue, &h->ptr, h->end, &rc);
if(rc) return -1;
}
return rc;
}
 
static const char * _signature_algorithms[] = {
"ecdsa_nistp256_with_sha256",
};
 
static int certificate_signature_tag (cxml_handler_t* const _h, cxml_tag_t * const tag)
{
int rc = 0;
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
if (cxml_tag_is_open(tag)){
void * key;
int alg = 0;
if(h->signer_type == 0){
// self signed certificate
key = h->verificationKey;
if(!key){
fprintf(stderr, "ERROR: Verification key attribute was not provided for self-signed certificate\n");
return -1;
}
}else{
const char * v = cxml_tag_attr_value(tag, "algorithm");
if (v){
alg = STR2ENUM(_signature_algorithms, v);
if (alg < 0){
fprintf(stderr, "%s: Unknown signature algorithm\n", v);
return -1;
}
}
 
if (h->signer == NULL){
fprintf(stderr, "ERROR: Signer certificate name shall be provided\n");
return -1;
}
 
// load signer certificate
int plen = strlen(_searchPath) + strlen(h->signer);
char * path = malloc(plen + 16);
 
cvstrncpy(path, plen + 16, _searchPath, "/", h->signer, ".v.prv.pem", NULL);
key = ecc_api_key_private_load(path);
if (key == NULL){
cvstrncpy(path, plen + 16, _searchPath, "/", h->signer, ".v.prv.bin", NULL);
key = ecc_api_key_private_load(path);
if (key == NULL){
cvstrncpy(path, plen + 16, _searchPath, "/", h->signer, ".v.prv.hex", NULL);
key = ecc_api_key_private_load(path);
if (key == NULL){
fprintf(stderr, "%s: Could not load issuing private key\n", path);
free(path);
return -1;
}
}
}
}
cint8_write(alg, &h->ptr, h->end, &rc);
rc = ecc_sign(key, h->buf, h->ptr-h->buf-1, &h->ptr, h->end-h->ptr);
}
return rc;
}
 
static int _Begin_Tag(cxml_handler_t* const h, cxml_tag_t * const tag)
{
fprintf(stderr, "WARNING: %s: Unknown tag", tag->name);
return 0;
}
 
static int _End_Tag(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return 0;
}
static int _Text(cxml_handler_t* const h, char * const text, int length)
{return 0;}
/trunk/tools/itscertgen/cshared/copts.c
0,0 → 1,789
/*********************************************************************
######################################################################
## copts.c
##
######################################################################
##
## Created by: Denis Filatov
## Date : 10.11.2005
##
##
## <DESCRIPTION>
##
## Copyright (c) 2003 - 2006
## Popular Telephony Inc.
## All rights reserved.
##
## STRICTLY CONFIDENTIAL.
## THIS SOURCE CODE IS A PROPERTY OF POPULAR TELEPHONY INC.
## IT IS PROTECTED BY INTERNATIONAL LAWS
## ANY UNAUTHORISED DISTRIBUTION OF THIS CODE IS PROHIBITED
##
######################################################################
*********************************************************************/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
 
#include "copts.h"
 
#ifdef _MSC_VER
#define inline __inline
#define strcasecmp _stricmp
#define strdup _strdup
#define _CRT_SECURE_NO_WARNINGS
#endif
 
#define COPT_AFLAG_ERROR 0x10000
#define COPT_AFLAG_PRESCAN 0x08000
#define COPT_AFLAG_LOPT 0x04000
#define COPT_AFLAG_AUTOHELP 0x02000
 
static int do_coptions (int argc, char* argv[], int flags, copt_t* opts);
static int set_option_value(copt_t* opt, const char * option, char* val);
static int copt_addr_assign(unsigned long* addr,const char* val);
inline
static int call_callback(const copt_t * opt, const char * option, const copt_value_t * value);
static void print_opt_help(FILE* f, copt_t* opt, int err, const char* errval);
 
int coptions(int argc, char* argv[], int flags, copt_t* opts)
{
int rc = 1, ahflag = 0;
copt_t *o;
 
if(0 == (flags & COPT_NOAUTOHELP)){
ahflag = COPT_AFLAG_AUTOHELP;
}
 
if(0 == (flags & COPT_NOCONFIG) || ahflag ){
for(o=opts; o->type != COPT_END; o++){
unsigned short t = o->type&COPT_TYPE_MASK;
 
/* check for config files */
if(0==(flags & COPT_NOCONFIG) && t == COPT_CFGFILE){
/* check for config options.
* just options with type COPT_CFGFILE
* will be processed */
rc = do_coptions(argc, argv, flags|COPT_AFLAG_PRESCAN|COPT_NOREORDER, opts);
if(rc < 0){
if(rc == COPT_EHELP){
if(0==(flags&COPT_NOHELP_MSG)){
coptions_help_ex(stdout, argv[0], flags, opts, NULL, NULL, NULL);
}
return rc;
}
if(0==(flags&COPT_NOERR_UNKNOWN)){
return rc;
}
}
if(o->vptr){
const char * cfgname = *((const char **)o->vptr);
if(cfgname){
rc = coptions_load(cfgname, NULL, flags, opts);
if(rc < 0){
if(0 == (flags&COPT_NOERR_MSG)){
fprintf(stderr, "%s: config load error\n", cfgname);
}
if(flags & COPT_ERR_CONFIG){
return rc;
}
}
}
}
} else if(t == COPT_HELP && ahflag){
/* check for autohelp */
ahflag = 0;
}
}
}
/* process other options except of COPT_CFGFILE */
return do_coptions(argc, argv, flags|ahflag, opts);
}
 
static void move_args(char * argv[], int to, int from, int count)
{
if( from > to){
while(from > to){
int i;
for(i=from; i<from+count; i++){
char * p = argv[i];
argv[i] = argv[i-1];
argv[i-1] = p;
}
from --;
}
}else{
while(from < to){
int i;
for(i=from+count-1; i>=from; i--){
char * p = argv[i];
argv[i] = argv[i+1];
argv[i+1] = p;
}
from ++;
}
}
}
 
static int do_coptions(int argc, char* argv[], int flags, copt_t* opts)
{
int i, rc;
int searchopts = 1;
copt_t* o=NULL;
copt_t* copt = NULL;
copt_t* onopt = NULL;
coptype_t t;
int nargc=argc;
 
assert(opts);
 
for(i=1; i<nargc; i++){
if(NULL == copt){
char * aopt = argv[i];
/* check for option */
if(searchopts && aopt[0]=='-' && aopt[1] != 0){
if(aopt[1] == '-'){
 
/* this is long option */
if(aopt[2] == 0){
/* -- - stop parsing options */
searchopts = 0;
continue;
}
 
/* check autohelp */
if(flags & COPT_AFLAG_AUTOHELP){
if(0==strcmp(aopt+2, "help")){
return COPT_EHELP;
}
}
 
/* search given option */
for(o = opts; COPT_END != o->type; o++){
int ol;
if(NULL == o->lopt) continue;
t = o->type&COPT_TYPE_MASK;
ol = (int)strlen(o->lopt);
if( (aopt[2+ol]==0 || aopt[2+ol]=='=')
&& 0==strncmp(o->lopt, aopt+2, ol)){
 
/* option found */
if(t == COPT_HELP){
return COPT_EHELP;
}
if(aopt[2+ol]=='='){
if(0==(flags&COPT_AFLAG_PRESCAN) || t == COPT_CFGFILE){
rc = set_option_value(o, argv[i], aopt+ol+3);
if(rc<0){
if(0==(flags&COPT_NOERR_MSG)){
print_opt_help(stderr, o, flags|COPT_AFLAG_ERROR, argv[i]);
}
if(0==(flags&COPT_NOERR_ARG)){
return -i;
}
}
}
}else if(t == COPT_BOOL || t == COPT_BOOLI){
if(0==(flags & COPT_AFLAG_PRESCAN)){
set_option_value(o, argv[i], NULL);
}
}else{
copt = o;
}
/* move this option argument to the end of list */
move_args(argv, argc-1, i, 1);
i--;
nargc--;
break;
}
}
if(COPT_END == o->type){
if(0==(flags&COPT_NOERR_MSG)){
fprintf(stderr, "Unknown option '%s'\n", argv[i]);
}
if(0==(flags & COPT_NOERR_UNKNOWN)){
return 0-i;
}
}
}else{
/* short options */
aopt++; /* skip first '-' */
while(*aopt){
 
/* check autohelp */
if(flags & COPT_AFLAG_AUTOHELP){
if(*aopt == 'h' || *aopt == '?'){
return COPT_EHELP;
}
}
 
for(o = opts; COPT_END != o->type; o++){
if(NULL == o->sopts) continue;
t = o->type&COPT_TYPE_MASK;
if(strchr(o->sopts, *aopt)){
/* option found */
char szopt[3]={'-',0,0};
szopt[1] = *aopt;
 
if(t == COPT_HELP){
return COPT_EHELP;
}
if(aopt[1] == 0){ /* -p -b 13 */
if(t == COPT_BOOL || t == COPT_BOOLI){
if(0 == (flags&COPT_AFLAG_PRESCAN)){
set_option_value(o, szopt, NULL);
}
}else{
copt = o;
}
aopt++;
}else if(aopt[1] == '='){ /* -p=123 */
if(0==(flags&COPT_AFLAG_PRESCAN) || t == COPT_CFGFILE){
rc = set_option_value(o, argv[i], aopt+2);
if(rc<0){
if(0==(flags&COPT_NOERR_MSG)){
print_opt_help(stderr, o, flags|COPT_AFLAG_ERROR, argv[i]);
}
if(0==(flags&COPT_NOERR_ARG)){
return -i;
}
}
}
while(*aopt) aopt++;
}else{ /* -p123*/
if(0==(flags&COPT_AFLAG_PRESCAN) || t == COPT_CFGFILE){
if( t == COPT_BOOL || t == COPT_BOOLI ){
set_option_value(o, szopt, NULL);
}else{
rc = set_option_value(o, szopt, aopt+1);
if(rc<0){
if(0==(flags&COPT_NOERR_MSG)){
print_opt_help(stderr, o, flags | COPT_AFLAG_ERROR, argv[i]);
}
if(0==(flags&COPT_NOERR_ARG)){
return -i;
}
}
}
}
while(*aopt) aopt++;
}
break;
}
}
if(COPT_END == o->type){
if(0==(flags&COPT_NOERR_MSG)){
fprintf(stderr, "Unknown option '%s'\n", argv[i]);
}
if(0==(flags & COPT_NOERR_UNKNOWN)){
return 0-i;
}
aopt++;
}else{
/* move this option argument to the end of list */
move_args(argv, argc-1, i, 1);
i--;
nargc--;
}
}
}
}else{
/* check for nonoption callback */
if(0 == (flags & COPT_AFLAG_PRESCAN)){
if(onopt == NULL){
onopt = (void*)-1;
for(o = opts; COPT_END != o->type; o++){
if(o->type & COPT_CALLBACK){
if(o->lopt == NULL && o->sopts == NULL && o->vptr){
onopt = o;
break;
}
}
}
}
if(onopt != (void*)-1){
copt_value_t v;
v.v_str = argv[i];
rc = call_callback(onopt, NULL, &v);
if(rc < 0){
if(rc == COPT_EHELP) return rc;
if(0==(flags&COPT_NOERR_ARG)){
return -i;
}
}
}
}
}
}else{ /* prev is option */
t = copt->type & COPT_TYPE_MASK;
if(0==(flags&COPT_AFLAG_PRESCAN) || t == COPT_CFGFILE){
rc = set_option_value(copt, argv[i-1], argv[i]);
if(rc < 0){
if(0==(flags&COPT_NOERR_MSG)){
print_opt_help(stderr, o, flags | COPT_AFLAG_ERROR, argv[i - 1]);
}
if(0==(flags&COPT_NOERR_ARG)){
return 0-i-1;
}
}
}
copt = NULL;
/* move this option argument to the end of list */
move_args(argv, argc-1, i, 1);
nargc--;
i--;
}
}
if(copt){
/* last option was not completed */
if(0==(flags&COPT_NOERR_MSG)){
print_opt_help(stderr, o, flags | COPT_AFLAG_ERROR, argv[i - 1]);
}
if(0==(flags&COPT_NOERR_ARG)){
return 0-i-1;
}
}
return nargc;
}
 
static int set_option_value(copt_t* opt, const char * arg, char* val)
{
char* np;
copt_value_t value;
 
value.v_boolean = 0;
 
switch(opt->type & COPT_TYPE_MASK){
case COPT_HELP:
case COPT_BOOL:
value.v_boolean = 1;
case COPT_BOOLI:
if(val){
if( val[0] == '0'
||0==strcasecmp(val, "false")
||0==strcasecmp(val, "no")
){
value.v_boolean = !value.v_boolean;
}else if( !isdigit(val[0])
&& strcasecmp(val, "true")
&& strcasecmp(val, "yes")
){
return -1;
}
}
break;
case COPT_LONG:
if(!val) return -1;
value.v_long = strtol(val, &np, 0);
if(*np != 0) return -1;
break;
case COPT_ULONG:
if(!val) return -1;
value.v_ulong = strtoul(val, &np, 0);
if(*np != 0) return -1;
break;
case COPT_SHORT:
if(!val || !opt->vptr) return -1;
value.v_long = strtol(val, &np, 0);
if(*np != 0) return -1;
if(value.v_long>SHRT_MAX || value.v_long<SHRT_MIN){
return -1;
}
value.v_short = (short) value.v_long;
break;
case COPT_USHORT:
if(!val || !opt->vptr) return -1;
value.v_ulong = strtoul(val, &np, 0);
if(*np != 0) return -1;
if(value.v_ulong>USHRT_MAX){
return -1;
}
value.v_ushort = (unsigned short) value.v_ulong;
break;
 
case COPT_CHAR:
if(!val || !opt->vptr) return -1;
if(0==val[1]){
value.v_char = val[0];
}else{
value.v_ulong = strtoul(val, &np, 0);
if(*np != 0) return -1;
if(value.v_ulong>UCHAR_MAX){
return -1;
}
value.v_char = (unsigned char)value.v_long;
}
break;
case COPT_STRENUM:
{
const char ** p = (const char**)opt->vptr;
for(; *p && strcmp(*p, val); p++);
if(NULL == *p){
return -1;
}
value.v_long = p - (const char**)opt->vptr;
}
break;
case COPT_STRLIST:
if(!opt->vptr || (opt->type & COPT_CALLBACK)) return -1;
case COPT_CFGFILE:
case COPT_STR:
value.v_str = val;
break;
case COPT_HOST:
if(0 > copt_addr_assign(&value.v_ulong, val)){
return -1;
}
break;
default:
return -1;
}
 
if(opt->type & COPT_CALLBACK){
return call_callback(opt, arg, &value);
}
 
switch(opt->type & COPT_TYPE_MASK){
case COPT_HELP:
case COPT_BOOL:
case COPT_BOOLI:
if(opt->vptr && opt->vptr != (void*)1){
*(int*)opt->vptr = value.v_boolean;
}else{
opt->vptr = ((char*)NULL) + value.v_boolean;
}
break;
case COPT_LONG:
case COPT_ULONG:
case COPT_CFGFILE:
case COPT_STR:
case COPT_HOST:
if(opt->vptr){
*(long*)opt->vptr = value.v_long;
}else{
opt->vptr = (void*)value.v_long;
}
break;
case COPT_STRLIST:
{
char ** p = opt->vptr;
*p = value.v_str;
opt->vptr = p + 1;
}
break;
case COPT_STRENUM:
opt->vptr = (void*)(((const char**)opt->vptr) + value.v_long);
break;
case COPT_SHORT:
case COPT_USHORT:
*(short*)opt->vptr = value.v_short;
break;
case COPT_CHAR:
*(char*)opt->vptr = value.v_char;
break;
default:
return -1;
};
return 0;
}
 
static int copt_addr_assign(unsigned long* addr,const char* val)
{
unsigned long n = 0;
unsigned long s = 0;
int cnt = 0;
while(*val){
if(*val == '.'){
if(cnt == 3){
return -1;
}
n = (n<<8) | s;
s = 0;
cnt++;
}else{
unsigned int c = *val - '0';
if(c > 9){
return -1;
}
s = s*10 + c;
}
val++;
}
if(cnt != 3){
return -1;
}
n = (n<<8) | s;
 
*addr = n;
return 0;
}
 
inline static int call_callback(const copt_t * opt, const char * option, const copt_value_t * value)
{
if(opt->vptr){
return ((copt_callback *)opt->vptr)(opt, option, value);
}
return -1;
}
 
void coptions_help_ex(FILE * f, const char * prgname, int flags, copt_t* opt, const char* usagestr,
const char* header, const char* footer)
{
const char * progname;
if(header){
fputs(header, f);
}
if(prgname){
progname = strrchr(prgname, '/');
if(progname) progname++;
else progname = prgname;
if(usagestr){
fprintf(f, "Usage: %s <options> %s\n", progname, usagestr);
}
fprintf(f, "Options:\n");
}else{
if(usagestr){
fprintf(f, "%s\n", usagestr);
}
}
while(opt->type != COPT_END){
if(opt->sopts || opt->lopt){
fprintf(f, " ");
print_opt_help(f, opt, flags, NULL);
}
opt++;
}
if(footer){
fputs(footer, f);
}
}
 
static int sprintf_option_value(const copt_t* const opt, char * const buf)
{
int ret = 0;
switch(opt->type&COPT_TYPE_MASK){
case COPT_BOOL:
if(opt->vptr && opt->vptr != (void*)1){
ret = sprintf(buf, "%s", ((*(int*)opt->vptr)?"true":"false"));
}else{
ret = sprintf(buf, "%s", ((opt->vptr)?"true":"false"));
}
break;
case COPT_BOOLI:
if(opt->vptr && opt->vptr != (void*)1){
ret = sprintf(buf, "%s", (*(int*)opt->vptr)?"false":"true");
}else{
ret = sprintf(buf, "%s", (opt->vptr)?"false":"true");
}
break;
case COPT_LONG:
ret = sprintf(buf, "%ld", *((long*)opt->vptr));
break;
case COPT_ULONG:
ret = sprintf(buf, "%lu", *((unsigned long*)opt->vptr));
break;
case COPT_SHORT:
ret = sprintf(buf, "%u", *((short*)opt->vptr));
break;
case COPT_USHORT:
ret = sprintf(buf, "%u", *((unsigned short*)opt->vptr));
break;
case COPT_CHAR:
ret = sprintf(buf, "%c", *((char*)opt->vptr));
break;
case COPT_STR:
case COPT_CFGFILE:
case COPT_STRENUM:
if(*(char**)opt->vptr)
ret = sprintf(buf, "%s", *(char**)opt->vptr);
else
ret = sprintf(buf, "NULL");
break;
case COPT_HOST:
{
unsigned int n = *(unsigned int*)opt->vptr;
sprintf(buf, "%u.%u.%u.%u",
n>>24, (n>>16)&0xFF, (n>>8)&0xFF, n&0xFF);
}
break;
}
return ret;
}
 
static const char* valnames[] = {
NULL, /* COPT_BOOL */
NULL, /* COPT_BOOLI */
"num", /* COPT_LONG */
"num", /* COPT_ULONG */
"num", /* COPT_SHORT */
"num", /* COPT_USHORT */
"chr", /* COPT_CHAR */
"str", /* COPT_STR */
"addr",/* COPT_HOST */
"str", /* COPT_STRLIST*/
"str", /* COPT_STRENUM*/
"file",/* COPT_CFGFILE*/
NULL, /* COPT_HELP */
};
 
static void print_opt_help(FILE* f, copt_t* opt, int flags, const char* errval)
{
char *p, sz_help[256];
p=sz_help;
int err = flags&COPT_AFLAG_ERROR;
int t=opt->type&COPT_TYPE_MASK;
if(opt->sopts){
const char* po = opt->sopts;
while(*po){
if(po != opt->sopts) (*p++) = '|';
*(p++)='-'; *(p++)=(*po);
po++;
}
if(valnames[t]){
p+=sprintf(p, " <%s>", valnames[t]);
}
}
if(opt->lopt){
if(opt->sopts) p+=sprintf(p, " | ");
p+=sprintf(p, "--%s", opt->lopt);
if(valnames[t]){
p+=sprintf(p, "=%s", valnames[t]);
}
}
if(opt->helpstr){
while(p-sz_help<35){
*(p++) = ' ';
}
p+=sprintf(p, " : %s", opt->helpstr);
}
if(err){
*(p++)='\n'; *(p++)='\t';
if(errval){
p+=sprintf(p, "%s ", errval);
}
p+=sprintf(p, "Unsupported value");
}else{
if (0 == (flags & COPT_HELP_NOVALUES)){
if (t != COPT_HELP && t != COPT_STRLIST && 0 == (opt->type&COPT_CALLBACK)){
/* print default value */
*(p++) = '[';
p += sprintf_option_value(opt, p);
*(p++) = ']';
*p = 0;
}
}
}
fprintf(f, "%s\n", sz_help);
}
 
int coptions_load(const char* filename, const char * section, int flags, copt_t* const opts)
{
char* buf;
int line = 0;
int err = 0;
int in_sect = 0;
FILE* f = fopen(filename, "r");
 
if(f == NULL){
if(0 == (flags & COPT_NOERR_MSG)){
perror(filename);
}
return COPT_ERROR;
}
 
buf = (char*)malloc(1024);
while(fgets(buf, 1024, f)){
char *e, *val=NULL, *key = buf;
copt_t * o;
unsigned short t;
 
err = 1;
line ++;
while(*key && isspace(*key)) key++;
if(0 == *key)continue;
/* search for section */
if(*key == '['){
if(section){
if(in_sect){
/* section loading finished */
in_sect =0;
break;
}
key++;
while(*key && isspace(*key)) key++;
e = strchr(key, ']');
if(e == NULL) goto error;
*e = 0;
if(0==strcmp(section, key)){
in_sect = 1;
}
}
continue;
}
 
if(section && 0== in_sect) continue;
if(*key == '#' || *key == ';') continue;
 
e = strchr(key, '=');
if(NULL == e) goto error;
val = e+1;
while(e>key && isspace(*(e-1)))e--;
if(e == key) goto error;
*e = 0;
 
while(*val && isspace(*val)) val ++;
 
for(o=opts; o->type != COPT_END; o++){
if(o->lopt && 0==strcmp(o->lopt, key))
break;
}
if(COPT_END == o->type) {
err = 2;
goto error;
}
t = o->type & COPT_TYPE_MASK;
 
e = val + strlen(val);
while(e>val && isspace(*(e-1))) *(--e) = 0;
 
if( t == COPT_STR
|| t == COPT_STRLIST
){
if(0==strcmp("NULL", val) || 0==strcmp("null", val)) val = NULL;
else val = strdup(val);
}
 
if(set_option_value(o, key, val)){
err = 3;
goto error;
}
 
continue;
 
error:
if(0 == (flags & COPT_NOERR_MSG)){
switch(err){
case 1:
fprintf(stderr, "%s:%d: Syntax error in config file\n", filename, line);
break;
case 2:
fprintf(stderr, "%s:%d: Option is unknown\n", filename, line);
break;
case 3:
fprintf(stderr, "%s:%d: Unsupported value: %s\n", filename, line, val);
break;
}
}
if(flags & COPT_ERR_CONFIG){
break;
}
}
free(buf);
fclose(f);
return 0;
}
/trunk/tools/itscertgen/cshared/cstr.c
0,0 → 1,189
#include "cstr.h"
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
 
int cstrlen(const char * str)
{
return str ? strlen(str) : 0;
}
 
char * cstrcpy(char * dst, const char * src)
{
if(!dst) return (char*)0;
int len = 0;
if(src){
len = strlen(src);
if(len){
memcpy(dst, src, len);
}
}
dst[len]=0;
return dst + len;
}
 
/* copy up to maxsize characters from src to dst and return pointer to the next byte after the end */
char * cstrncpy(char * dst, int maxsize, const char * src)
{
if(!dst) return (char*)0;
unsigned int ms = maxsize;
unsigned int len = 0;
if(src && ms > 0){
len = strlen(src);
if(len > ms){
len = ms;
if(len){
memcpy(dst, src, len);
}
}
}
dst[len]=0;
return dst + len;
}
 
/* copy up to maxsize characters from src to dst and return pointer to the next byte after the end */
char * cvstrncpy(char * dst, int maxsize, const char * ptr, ...)
{
va_list ap;
char * p = dst;
const char * r = ptr;
unsigned int ms = maxsize;
if(ms > 0){
va_start(ap, ptr);
while(r){
unsigned int len = strlen(r);
if(len > ms) len = ms;
memcpy(p, r, len);
p += len;
ms -= len;
r = va_arg(ap, const char*);
}
va_end(ap);
*p = 0;
}
return p;
}
 
char * cstralloc(int size)
{
return (char*)malloc((size+0xF)&(~0xF));
}
char * cstrdup(const char * str)
{
char * ret = NULL;
if(str){
int len = strlen(str);
if(len){
ret = cstralloc(len);
memcpy(ret, str, len+1);
}
}
return ret;
}
 
char * cstrndup(const char * str, int max_size)
{
char * ret = NULL;
unsigned int ms = max_size;
if(str){
unsigned int len = strlen(str);
if(len>ms) len=ms;
if(len){
ret = cstralloc(len);
memcpy(ret, str, len);
ret[len] = 0;
}
}
return ret;
}
 
char * cvstrdup(const char * ptr, ...)
{
va_list ap;
int len = 0;
char *dst, *p;
const char * r;
if(!ptr) return (char*)ptr;
 
// calculate size
r = ptr;
va_start(ap, ptr);
while(r){
len += strlen(r);
r = va_arg(ap, const char*);
}
va_end(ap);
p = dst = cstralloc(len+1);
if(dst){
r = ptr;
va_start(ap, ptr);
while(r){
len = strlen(r);
memcpy(p, r, len);
p += len;
r = va_arg(ap, const char*);
}
va_end(ap);
*p = 0;
}
return dst;
}
 
char * cstrnload(char * dst, int max_size, const char * path)
{
FILE * f = fopen(path, "rb");
unsigned long len;
unsigned long ms = max_size;
if (!f) return NULL;
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
if (len > ms) len = ms;
ms = fread(dst, 1, len, f);
fclose(f);
if ((int)ms < 0){
return NULL;
}
dst[len] = 0;
return dst + len;
}
 
char * cstraload(char ** p, const char * path)
{
char * ret = NULL;
FILE * f = fopen(path, "rb");
int len;
if (f){
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
if (len > 0){
ret = malloc(len);
if (ret){
int ms = fread(ret, 1, len, f);
if (ms < len){
free(ret);
*p = ret = NULL;
}
else{
*p = ret;
ret += len;
}
}
}
fclose(f);
}
return ret;
}
 
const char * cstrlastpathelement(const char * str)
{
const char * p = strrchr(str, '/');
const char * p2 = strrchr(str, '/');
if(p<p2)p=p2;
else if(p == NULL) p = str;
return p;
}
/trunk/tools/itscertgen/cshared/cstr.h
0,0 → 1,41
#ifndef CSTR_H
#define CSTR_H
#ifdef __cplusplus
extern "C" {
#endif
 
int cstrlen(const char * str);
/* copy src to dst and return pointer to the next byte after the end */
char * cstrcpy(char * dst, const char * src);
 
/* copy up to maxsize characters from src to dst and return pointer to the next byte after the end */
char * cstrncpy(char * dst, int maxsize, const char * src);
 
/* copy up to maxsize characters from parameters to dst and return pointer to the next byte after the end */
char * cvstrncpy(char * dst, int maxsize, const char * ptr, ...);
 
 
/* allocate copy of the str */
char * cstralloc(int size);
char * cstrdup(const char * str);
char * cstrndup(const char * str, int max_size);
 
 
/* allocate new str and collect all paramaters */
char * cvstrdup(const char * ptr, ...);
 
char * cstrnload(char * dst, int max_size, const char * path);
char * cstraload(char ** p, const char * path);
 
const char * cstrlastpathelement(const char * str);
 
int cstr_write(const char * const p, char ** const ptr, const char * const end, int * const error);
int cstr_read (char * const p, const char ** const ptr, const char * const end, int * const error);
 
int cstrn_write(const char * const p, int length, char ** const ptr, const char * const end, int * const error);
int cstrn_read (char * const p, int length, const char ** const ptr, const char * const end, int * const error);
 
#ifdef __cplusplus
}
#endif
#endif
/trunk/tools/itscertgen/cshared/cserialize.c
0,0 → 1,250
#include "cserialize.h"
#include <errno.h>
 
#ifdef __GNUC__
#define cint_cpy(D,N,S) __builtin_memcpy((char*)(D),N,S)
#else
#include <string.h>
#define cint_cpy(D,N,S) memcpy((char*)(D),N,S)
uint64_t cint64_swap(uint64_t);
uint32_t cint32_swap(uint32_t);
uint16_t cint16_swap(uint16_t);
static const uint64_t one64 = 1;
#endif
 
int _cint64_write(const uint64_t value, char** const ptr, const char* const end, int * const error)
{
register unsigned char* p = (unsigned char*)*ptr;
if(p + 8 <= (unsigned char*)end){
if(0 == (((int)p)&0x7)){
*((uint64_t*)p) = cint64_hton(value);
p+=8;
}else{
int i;
for(i=7; i>=0; i--){
*p++ = (value>>(8*i))&0xFF;
}
}
*ptr = (char*)p;
if(error) *error = 0;
return 0;
}
if(error) *error = ENOMEM;
return -1;
}
 
int _cint32_write(const uint32_t value, char** const ptr, const char* const end, int * const error)
{
register unsigned char* p = (unsigned char*)*ptr;
if(p + 4 <= (unsigned char*)end){
if(0 == (((int)p)&0x3)){
*((uint32_t*)p) = cint32_hton(value);
p+=4;
}else{
int i;
for(i=3; i>=0; i--){
*p++ = (value>>(8*i))&0xFF;
}
}
*ptr = (char*)p;
if(error) *error = 0;
return 0;
}
if(error) *error = ENOMEM;
return -1;
}
 
int _cint16_write(const uint16_t value, char** const ptr, const char* const end, int * const error)
{
register unsigned char* p = (unsigned char*)*ptr;
if(p + 2 <= (unsigned char*)end){
*p++ = (value>>8)&0xFF;
*p++ = value&0xFF;
*ptr = (char*)p;
if(error) *error = 0;
return 0;
}
if(error) *error = ENOMEM;
return -1;
}
 
int _cint8_write(const uint8_t value, char** const ptr, const char* const end, int * const error)
{
if(*ptr < end) {
*((uint8_t*)*ptr) = value;
(*ptr) ++;
if(error) *error = 0;
return 0;
}
if(error) *error = ENOMEM;
return -1;
}
 
uint64_t cint64_read(const char** const ptr, const char* const end, int * const error)
{
uint64_t value;
register const uint8_t * p = (const uint8_t *)*ptr;
if(p + 8 <= (const uint8_t *)end) {
if(0 == (((int)p)&0x7)){
value = cint64_hton(*p);
*ptr = (char*)(p+8);
}else{
int i;
value=0;
for(i=0; i<8; i++){
value = (value<<8) | *(p++);
}
*ptr = (char*)p;
}
if(error) *error = 0;
}else{
value = (unsigned)-1;
if(error) *error = ENOMEM;
}
return value;
}
 
uint32_t cint32_read(const char** const ptr, const char* const end, int * const error)
{
uint32_t value;
register const uint8_t * p = (const uint8_t*)*ptr;
if(p + 4 <= (const uint8_t *)end) {
value = ((uint32_t)p[0])<<24 | ((uint32_t)p[1])<<16 | ((uint32_t)p[2])<<8 | p[3];
*ptr = (char*)(p+4);
if(error) *error = 0;
}else{
value = (unsigned)-1;
if(error) *error = ENOMEM;
}
return value;
}
 
uint16_t cint16_read(const char** const ptr, const char* const end, int * const error)
{
uint32_t value;
register const uint8_t * p = (const uint8_t*)*ptr;
if(p + 2 > (const uint8_t*)end) {
value = (unsigned)-1;
if(error) *error = ENOMEM;
}else{
value = ((uint16_t)p[0])<<8 | p[1];
*ptr = (const char*)(p+2);
if(error) *error = 0;
}
return value;
}
 
uint8_t cint8_read(const char** const ptr, const char* const end, int * const error)
{
if(error) *error = 0;
if(*ptr >= end) {
if(error) *error = ENOMEM;
return -1;
}
return *(const uint8_t*)((*ptr)++);
}
 
int cintx_bytecount(uint64_t value)
{
int num_bytes = 0;
#ifdef __GNUC__
if(value){
num_bytes = (64 + 6 - __builtin_clzll(value))/7;
}else{
num_bytes = 1;
}
#else
uint64_t overflow = 0;
while(value >= overflow){
num_bytes++;
overflow = one64 << (7*num_bytes);
}
#endif
return num_bytes;
}
 
int _cintx_write (const uint64_t value, char ** const ptr, const char * const end, int * const error)
{
int num_bytes = 0;
uint8_t c;
uint8_t *out = (uint8_t*)(*ptr);
num_bytes = cintx_bytecount(value);
if(num_bytes > 8 || out+num_bytes > ((const uint8_t*)end)){
if(error) *error = ENOMEM;
return -1;
}
num_bytes--;
c = ~((1<<(8-num_bytes))-1);
c |= (value >> (num_bytes*8)) & 0xFF;
*out++ = c;
while(num_bytes){
num_bytes--;
c = (value >> (num_bytes*8)) & 0xFF;
*out++ = c;
}
*ptr = (char*)out;
if(error) *error = 0;
return 0;
}
 
static int countof1(int c)
{
int r = 0;
while(c & 0x80){
#ifdef __GNUC__
return 1 + __builtin_clrsb(c<<24);
#else
r++;
c<<=1;
#endif
}
return r;
}
 
uint64_t cintx_read(const char** const ptr, const char* const end, int * const error)
{
uint8_t c;
const uint8_t* in;
int i, lead_ones;
in = (const uint8_t*)*ptr;
if(in <= (const uint8_t*)end){
c = *in;
lead_ones = countof1(c);
if(in + 1 + lead_ones <= (const uint8_t*)end) {
uint64_t value;
value = c & ((1<<(7-lead_ones))-1);
for(i=1; i<=lead_ones; i++){
value = (value<<8) | in[i];
}
*ptr = (const char*)(in + 1 + lead_ones);
if(error) *error = 0;
return value;
}
}
if(error) *error = ENOMEM;
return -1;
}
 
int cbuf_write(const void * const p, int length, char ** const ptr, const char * const end, int * const error)
{
if(error) *error = 0;
if((*ptr) + length >= end) {
if(error) *error = ENOMEM;
return -1;
}
cint_cpy(*ptr, p, length);
*ptr = (*ptr) + length;
return 0;
}
 
int cbuf_read (void * const p, int length, const char ** const ptr, const char * const end, int * const error)
{
if(error) *error = 0;
if((*ptr) + length >= end) {
if(error) *error = ENOMEM;
return -1;
}
cint_cpy(p, *ptr, length);
*ptr = (*ptr) + length;
return 0;
}
/trunk/tools/itscertgen/cshared/cserialize.h
0,0 → 1,62
#ifndef cint_h
#define cint_h
#include <stdint.h>
 
#ifdef __cplusplus
extern "C" {
#endif
 
#if defined(__GNUC__)
# define cint64_swap(X) __builtin_bswap64(X)
# define cint32_swap(X) __builtin_bswap32(X)
# define cint16_swap(X) __builtin_bswap16(X)
#elif defined (_MSC_VER)
# define cint64_swap(X) _byteswap_uint64(X)
# define cint32_swap(X) _byteswap_ulong (X)
# define cint16_swap(X) _byteswap_ushort(X)
#define __ORDER_LITTLE_ENDIAN__ 1
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#else
uint64_t cint64_swap(const uint64_t);
uint32_t cint32_swap(const uint32_t);
uint16_t cint16_swap(const uint16_t);
#endif
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define cint64_hton(X) cint64_swap(X)
# define cint32_hton(X) cint32_swap(X)
# define cint16_hton(X) cint16_swap(X)
#else
# define cint64_hton(X) (X)
# define cint32_hton(X) (X)
# define cint16_hton(X) (X)
#endif /* __BYTE_ORDER__ */
 
/* serialisation */
int _cint64_write(const uint64_t n, char ** const ptr, const char * const end, int * const error);
int _cint32_write(const uint32_t n, char ** const ptr, const char * const end, int * const error);
int _cint16_write(const uint16_t n, char ** const ptr, const char * const end, int * const error);
int _cint8_write (const uint8_t n, char ** const ptr, const char * const end, int * const error);
int _cintx_write (const uint64_t n, char ** const ptr, const char * const end, int * const error);
 
#define cint64_write(N,P,S,E) _cint64_write((uint64_t)(N), P, S, E)
#define cint32_write(N,P,S,E) _cint32_write((uint32_t)(N), P, S, E)
#define cint16_write(N,P,S,E) _cint16_write((uint16_t)(N), P, S, E)
#define cint8_write(N,P,S,E) _cint8_write ((uint8_t)(N), P, S, E)
#define cintx_write(N,P,S,E) _cintx_write ((uint32_t)(N), P, S, E)
uint64_t cint64_read (const char ** const ptr, const char * const end, int * const error);
uint32_t cint32_read (const char ** const ptr, const char * const end, int * const error);
uint16_t cint16_read (const char ** const ptr, const char * const end, int * const error);
uint8_t cint8_read (const char ** const ptr, const char * const end, int * const error);
uint64_t cintx_read (const char ** const ptr, const char * const end, int * const error);
 
int cintx_bytecount(uint64_t);
 
int cbuf_write(const void * const p, int length, char ** const ptr, const char * const end, int * const error);
int cbuf_read (void * const p, int length, const char ** const ptr, const char * const end, int * const error);
 
#ifdef __cplusplus
}
#endif
 
#endif
/trunk/tools/itscertgen/cshared/cshared.vcxproj
0,0 → 1,89
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="copts.c" />
<ClCompile Include="cserialize.c" />
<ClCompile Include="cstr.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="copts.h" />
<ClInclude Include="cserialize.h" />
<ClInclude Include="cstr.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>cshared</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)msvc\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)msvc\$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
/trunk/tools/itscertgen/cshared/Makefile
0,0 → 1,13
BUILDROOT = ..
PROJECT = cshared
DEBUG = yes
testdir = tests
 
alibs = $(PROJECT)
solibs = $(PROJECT)
 
sources := copts.c cserialize.c cstr.c
headers := copts.h cserialize.h cstr.h
tests := test_copts.c
 
include ../common.mk
/trunk/tools/itscertgen/cshared/copts.h
0,0 → 1,238
/*********************************************************************
######################################################################
## copts.h
##
######################################################################
##
## Created by: Denis Filatov
## Date : 10.11.2005
##
##
## C command line arguments and simple config file parser
##
## Copyright (c) 2003 - 2007
## All rights reserved.
##
## STRICTLY CONFIDENTIAL.
## THIS SOURCE CODE IS A PROPERTY OF POPULAR TELEPHONY INC.
## IT IS PROTECTED BY INTERNATIONAL LAWS
## ANY UNAUTHORISED DISTRIBUTION OF THIS CODE IS PROHIBITED
##
######################################################################
*********************************************************************/
#ifndef copts_h
#define copts_h
#include <stdio.h>
 
#ifdef __cplusplus
extern "C" {
#endif
 
/** @defgroup COPTS copts - Programm line option processing.
* @{ */
 
#ifndef DOXYGEN
typedef struct copt_t copt_t;
typedef enum coptflag_t coptflag_t;
typedef enum coptype_t coptype_t;
typedef enum copterr_t copterr_t;
#endif
/** @enum coptype_t
* Option types definitions.
*/
enum coptype_t{
COPT_BOOL , /**< Boolean option. Doesn't wants for argument.*/
COPT_BOOLI, /**< Inverted Boolean option. Doesn't wants for argument. */
COPT_LONG , /**< Wants for long argument */
COPT_ULONG, /**< Wants for unsigned long argument */
COPT_SHORT, /**< Wants for short (16 bit) argument */
COPT_USHORT, /**< Wants for unsigned short argument */
COPT_CHAR , /**< Wants for char or unsigned char argument */
COPT_STR , /**< Wants for string (const char *) arguments */
COPT_HOST, /**< Wants for string (const char *) arguments. Checks url syntax. */
COPT_STRLIST, /**< Wants for string list argument (const char *[])
* Every time when this opion will be occuren in argv
* the value will be assigned to given pointer and
* this pointer will be incremented. */
COPT_STRENUM, /**< Wants for one of the string in the array given by vptr)
* Array of strings must be terminated by NULL pointer.
* After option found the vptr pointer will point to the
* to the element given by option */
COPT_CFGFILE, /**< Wants for string (const char *) arguments.
* Treat it as config file name and load if found.
* If one or more config file options are exists in copt_t list
* this options will be executed before any other options parsing */
COPT_HELP, /**< Do not wants for argument.
* If this option is occured in command line parsing will be
* terminated imediate and COPT_EHELP will be returned */
 
 
COPT_TYPE_MASK = 0x00FF, /**< Option type mask. For internal usage. */
COPT_CALLBACK = 0x4000, /**< Mask. Can be or-ed with any other option.
* That's mean treat vptr as a callback addres to call
* when option is occured */
COPT_CONFIG = 0x8000, /**< Mask. Can be or-ed with any other option.
* That's mean this option can be reached from config file
* and have to be writen to.*/
 
COPT_END = 0xFFFF, /**< End of options.
* If vptr is not NULL, treat it as callback to call for unknown
* options and non-option values */
};
 
#define COPT_INT COPT_LONG
#define COPT_UINT COPT_ULONG
#define COPT_IBOOL COPT_BOOLI
 
/** Main options item.
* Have to be used to define options items.
* Short and long options can be defined.
* Possible options notations:
* - Boolean options:
* - -o
* - --option
* - Other types except of boolean:
* - -o value
* - -o=value
* - --option=value
*/
struct copt_t
{
const char* sopts; /**< Short options. */
const char* lopt; /**< Long option. */
const coptype_t type; /**< Option type ( see @ref coptype_t ). */
void* vptr; /**< Option variable pointer. */
const char* helpstr; /**< Option help string. */
};
 
/**
* Execute option parser.
* @param argc Command line parameters count (from arguments of main() for example).
* @param argv Array of command line parameters.
* @param flags Configuration flags ( @ref coptflag_t ).
* @param opts Array of possible options. Must be finished by item with COPT_END type.
* @return <ul><li>On success returns the index of the first option argument in the arguments array.<li>On error returns negative index of the invalid option in the arguments array.</ul>
*/
int coptions(int argc, char* argv[], int flags, copt_t* opts);
 
/** Get enum index from the option variable.
* @param opts @ref copt_t array.
* @param idx Index of the enum option in the array.
* @param ptr The initial value of the @a vptr field of the opion array item.
* @return the integer enum value of the selected item.
*/
#define copts_enum_value(opts,idx,ptr) \
((const char **)((opts)[idx]).vptr) - ((const char **)(ptr))
 
/**
* Load options config file.
* @param filename File path to load.
* @param section If not NULL then try to find the last occurance of the
* given section or load the file complet.
* @param flags Configuration flags ( see @ref coptflag_t ).
* @param opts The Array of possible option records. Must be finished
* by the item with COPT_END type.
* @return
<ul><li>On success returns 0.<li>On error returns negative line number of the invalid expression.</ul>
*/
int coptions_load(const char* filename, const char * section, int flags, copt_t* const opts);
 
/**
* Save current options to the file
*/
int coptions_save(const char* filename, const copt_t* const opts);
 
/**
* Save current options to already opened file
*/
int coptions_fsave(FILE * fd, const copt_t* const opts);
 
/**
* Generate and print the help page.
* @param fd File descriptor to print the resulting help page.
* @param prgname Application name. Can be taken from argv[0].
* @param opt Options array.
* @param usagestr The string to print before option list.
* @param header Help page header.
* @param footer Help page footer.
 
*/
void coptions_help_ex(FILE * fd, const char * prgname, int flags, copt_t* opt, const char* usagestr,
const char* header, const char* footer);
/** The lite version of the @ref coptions_help_ex.
* @param fd File descriptor to print the resulting help page.
* @param prgname Application name. Can be taken from argv[0].
* @param opt Options array.
* @param usagestr The string to print before option list.
*/
#define coptions_help(fd,prgname,flags,opt,usagestr) \
coptions_help_ex(fd,prgname,flags,opt,usagestr,NULL,NULL)
 
/** Wild value definition */
typedef union{
int v_boolean;
signed short v_short;
unsigned short v_ushort;
signed long v_long;
unsigned long v_ulong;
char v_char;
char * v_str;
}copt_value_t;
 
/** The type of callback function to be called for the option having
@ref COPT_CALLBACK bit set in the @e type field of the @ref copt_t structure.
 
These functions must return zero if option was successfully processed,
@ref COPT_EHELP to generate option help string or negative value when
some error was occured.
@param opt The current item of the options array.
@param option String option given.
@param value Pointer to the option value.
*/
 
typedef int copt_callback(const copt_t * opt, const char * option, const copt_value_t * value);
 
/** Inverted Boolean True. */
#define IBOOL_YES ((void*)-1)
 
/** @enum coptflag_t
Option flag mask values.
*/
enum coptflag_t
{
COPT_DEFAULT = 0x0000, /**< No special flags given. */
COPT_NOAUTOHELP = 0x0001, /**< Does not provide automatic help messages. */
COPT_NOCONFIG = 0x0002, /**< Does not search for config files. */
COPT_NOREORDER = 0x0004, /**< Does not reorder command line array. */
COPT_NOERR_MSG = 0x0010, /**< Be silent. */
COPT_NOERR_UNKNOWN = 0x0020, /**< Treat unknown options as non-option args.*/
COPT_NOERR_ARG = 0x0040, /**< Does not produce an error if the required
option's argument is omited or have
incompatible type. */
COPT_NOERR = 0x0070, /**< Does not produce any errors. */
COPT_ERR_CONFIG = 0x0080, /**< Does not produce config errors. */
COPT_NOHELP_MSG = 0x0100, /**< Does not print help messages. */
COPT_HELP_NOVALUES = 0x0200, /**< Does not print default values. */
};
 
/** @{
@ref coptions return codes.
*/
/** Help option (-h or --help) vaw invoked. Need to print help page.*/
#define COPT_EHELP ((int)(0x80000001))
/** Some error was occured.*/
#define COPT_ERROR ((int)(0x80000002))
#define COPT_ERC(rc) (rc < 0 && 0==(rc & 0x8000000))
/**@}*/
 
/** @} */
 
/**
* @example test_copts.c
*/
 
#ifdef __cplusplus
}
#endif
 
#endif
/trunk/tools/itscertgen/cshared/tests/test_copts.c
0,0 → 1,105
#include "../copts.h"
static const char* logfile = NULL;
static int use_daemon = 1;
static unsigned short port = 0;
static unsigned long addr = 0;
static const char* cfgfile = "not set";
 
static char* strs[20];
static const char * strenum[] = {
"strenum0",
"strenum1",
"strenum2",
"strenum3",
"strenum4",
NULL
};
 
 
static int str_callback(const copt_t * opt, const char * option, copt_value_t * value)
{
printf("STR_CALLBACK: %s: %s\n", option, value->v_str);
return 0;
}
static int long_callback(const copt_t * opt, const char * option, copt_value_t * value)
{
printf("LONG_CALLBACK: %s %ld\n", option, value->v_long);
return 0;
}
 
static int short_callback(const copt_t * opt, const char * option, copt_value_t * value)
{
printf("SHORT_CALLBACK: %s %d\n", option, value->v_short);
return 0;
}
 
static int arg_callback(const copt_t * opt, const char * option, copt_value_t * value)
{
printf("ARGUMENT: %s \n", value->v_str);
return 0;
}
 
static copt_t options [] = {
{"h?", "help", COPT_HELP, NULL , "Print this help page"},
{"C", "config", COPT_CFGFILE, &cfgfile , "Config file" },
{"b", "boolvalue", COPT_BOOL |COPT_CONFIG, NULL , "Bool test value" },
{"d", "nodaemon", COPT_BOOLI |COPT_CONFIG, &use_daemon , "Start as daemon" },
{"l", "logfile", COPT_STR |COPT_CONFIG, &logfile , "Use this log file" },
{"e", "strenum", COPT_STRENUM|COPT_CONFIG, &strenum[0] , "String enum values" },
{"pP", "port", COPT_USHORT |COPT_CONFIG, &port , "Bind to port" },
{"aA", "addr", COPT_HOST |COPT_CONFIG, &addr , "Bind to ip-address" },
{"s", "strings", COPT_STRLIST|COPT_CONFIG, &strs[0] , "String list" },
{"S", "str_cb", COPT_STR |COPT_CALLBACK,&str_callback,"String throw callback" },
{"L", "l_cb", COPT_LONG |COPT_CALLBACK,&long_callback,"Long throw callback" },
{"H", "s_cb", COPT_SHORT |COPT_CALLBACK,&short_callback,"Short throw callback" },
{NULL, NULL, COPT_CALLBACK, &arg_callback,NULL },
{NULL, NULL, COPT_END, NULL , NULL }
};
 
int main(int argc, char** argv)
{
int i, j;
int flags = COPT_DEFAULT|COPT_NOERR_UNKNOWN|COPT_NOAUTOHELP;
 
i = coptions(argc, argv, flags, options);
 
if(i<0){
if(COPT_ERC(i)){
if(i == COPT_EHELP){
coptions_help(stdout, argv[0], options, "nonarg params");
}
}else{
printf("Unknown option %s\n", argv[0-i]);
}
}
 
printf("help = %s\n", options[0].vptr?"yes":"no");
printf("bool = %s\n", options[1].vptr?"yes":"no");
printf("use_daemon = %s\n", use_daemon?"yes":"no");
printf("logfile = %s\n", logfile);
printf("port = %d\n", port);
printf("addr = %08lX\n", addr);
printf("strenum=%d(%s)\n",
(int)(((const char **)options[5].vptr) - &strenum[0]),
*(const char **)options[5].vptr );
{
char ** b = &strs[0];
char ** e = options[8].vptr;
printf("strlist: count=%d\n", (int)(e - b));
while(b < e){
printf("\t%s\n", *b);
b++;
}
}
if(i>0){
printf("\nNonoptions:\n");
for(j=1; j<i; j++){
printf("\targv[%d]=%s\n", j, argv[j]);
}
printf("\nOptions in order:\n");
for(; j<argc; j++){
printf("\targv[%d]=%s\n", j, argv[j]);
}
}
return 0;
}
/trunk/tools/itscertgen/cxml/cxml.c
0,0 → 1,599
#include "cxml.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
 
#ifdef _MSC_VER
#define inline __inline
#endif
 
#ifdef DEBUG
//#define DEBUG_XML_STRUCTURE
#include <signal.h>
#endif
 
#ifdef GNUC
#define CXML_INC(X) __sync_add_and_fetch(X, 1)
#define CXML_DEC(X) __sync_sub_and_fetch(X, 1)
#else
#define CXML_INC(X) (++(*((int*)(X))))
#define CXML_DEC(X) (--(*((int*)(X))))
#endif
typedef unsigned int uint;
 
#define CXML_BUFFER_SIZE 1024
 
#ifndef _CXML_HANDLER_PARSE_STREAM_DEFINED
int cxml_handler_parse_stream(void * const h, FILE * f);
#endif
void cxml_handler_add_default_entities(void * const h);
 
void cxml_handler_init(void * const p, const cxml_handler_class * const Class)
{
cxml_handler_t * h = p;
memset(h, 0, Class->size);
h->Class = Class;
h->File = NULL;
h->Version = NULL;
h->Encoding = NULL;
cxml_handler_add_default_entities(h);
}
 
void * cxml_handler_new(const cxml_handler_class * const Class)
{
cxml_handler_t * h;
unsigned int size;
if(Class->size < sizeof(cxml_handler_t))
size = sizeof(cxml_handler_t);
else
size = Class->size;
if(Class->alloc){
h = Class->alloc(size);
}else{
h = malloc(size);
}
cxml_handler_init(h, Class);
return h;
}
 
void cxml_handler_close(void * const p)
{
cxml_handler_t * h = (cxml_handler_t*)p;
if(h->WaitTag) {
h->WaitTag = NULL;
}
h->File = NULL;
h->Version = NULL;
h->Encoding = NULL;
}
 
void cxml_handler_delete( void * const p )
{
cxml_free_f * f_free;
cxml_handler_t * h = (cxml_handler_t*)p;
f_free = (h->Class->free) ? h->Class->free : free;
cxml_handler_close(p);
f_free(p);
}
 
void cxml_wait_for_close(void * const p, cxml_tag_t * const tag)
{
cxml_handler_t * h = (cxml_handler_t*)p;
h->WaitTag = tag->name;
}
 
 
cxml_tag_t * cxml_tag_new(void * const p, const cxml_tag_type type, const char * const name)
{
cxml_tag_t * t;
cxml_handler_t * h = (cxml_handler_t*)p;
 
if(h->Class->tag_alloc){
t = h->Class->tag_alloc(sizeof(cxml_tag_t));
}else{
t = cxml_alloc(h, sizeof(cxml_tag_t));
}
t->ucount = 1;
t->type = type;
t->name = name;
t->attributes = NULL;
return t;
}
 
void cxml_tag_free(void * const p, cxml_tag_t * const t)
{
if(0 == CXML_DEC(&t->ucount)){
cxml_handler_t * h = (cxml_handler_t*)p;
cxml_attr_t * a = t->attributes;
while(a){
cxml_attr_t * n = a->next;
cxml_attr_free(h, a);
a = n;
}
if(h->Class->tag_free){
h->Class->tag_free(t);
}else if(h->Class->free){
h->Class->free(t);
}else{
free(t);
}
}
}
 
cxml_tag_t * cxml_tag_use(cxml_tag_t * const t)
{
CXML_INC(&t->ucount);
return t;
}
 
cxml_attr_t * cxml_attr_new(void * const p, const char * const name)
{
cxml_attr_t * a = cxml_alloc(p, sizeof(cxml_attr_t));
a->name = name;
a->value = NULL;
return a;
}
 
void cxml_attr_free(void * const p, cxml_attr_t * const a)
{
cxml_free(p, a);
}
 
int cxml_tag_is(const cxml_tag_t * const tag, const char * const tagname)
{
return 0 == strcmp(tag->name, tagname);
}
 
static inline cxml_attr_t * cxml_tag_attr_find(cxml_tag_t * const tag, const char * const key)
{
cxml_attr_t * a = tag->attributes;
while(a && strcmp(a->name, key))
a = a->next;
return a;
}
 
int cxml_tag_has_attr(cxml_tag_t * const tag, const char * const key)
{
return cxml_tag_attr_find(tag, key) ? 1 : 0;
}
 
const char * cxml_tag_attr_value(cxml_tag_t * const tag, const char * const key)
{
cxml_attr_t * a = cxml_tag_attr_find(tag, key);
if(a){
return a->value;
}
return NULL;
}
 
int cxml_tag_attr_boolean(cxml_tag_t * const tag, const char * const key)
{
cxml_attr_t * a = cxml_tag_attr_find(tag, key);
if(a && a->value){
const char * p = a->value;
if(isdigit(*p)){
while(*p == '0')p++;
return isdigit(*p) ? 1 : 0 ;
}
 
if(0 == strcmp(p, "true") ||
0 == strcmp(p, "yes") ||
0 == strcmp(p, "on")){
return 1;
}
}
return 0;
}
 
int cxml_tag_attr_int(cxml_tag_t * const tag, const char * const key)
{
int ret=-1;
cxml_attr_t * a = cxml_tag_attr_find(tag, key);
if(a && a->value){
char *e;
const char *b = a->value;
while(isspace(*b))b++;
if(*b){
ret = strtol(b, &e, 0);
while(isspace(*e))e++;
if(*e != 0){
ret = -1;
}
}
}
return ret;
}
 
uint cxml_tag_attr_uint(cxml_tag_t * const tag, const char * const key)
{
uint ret=(uint)-1;
cxml_attr_t * a = cxml_tag_attr_find(tag, key);
if(a && a->value){
char *e;
const char *b = a->value;
while(isspace(*b))b++;
if(*b){
ret = strtoul(b, &e, 0);
while(isspace(*e))e++;
if(*e != 0){
ret = (uint)-1;
}
}
}
return ret;
}
 
//typedef int (*cxml_tag_f) (cxml_handler_t* const h, cxml_tag_t * const tag);
 
static int cxml_call_handler(cxml_tag_f * handler, cxml_handler_t * const h, cxml_tag_t * const tag)
{
#ifdef DEBUG_XML_STRUCTURE
printf("<%s%s>\n", (tag->type&CXML_TAG_CLOSE)?"/":"",tag->name);
#endif
return handler ? handler(h, tag) : 0;
}
 
static int cxml_handler_post_text(cxml_handler_t * const h, char* b, char* e)
{
int ret = 0;
if(e>b){
if(h->Class->text){
char ch = *e;
*e = 0;
ret = cxml_text_decode(h, b, e-b);
if(0 <= ret ){
ret = h->Class->text(h, b, ret);
}
*e = ch;
}
}
ASSERT_RETURN(ret);
}
 
static int istagend(uint const type, const char* ch)
{
switch(type){
case CXML_TAG_SYSTEM:
return (*ch == '?' && ch[1] == '>');
case CXML_TAG_COMMENT:
return (ch[0] == '-' && ch[1] == '-' && ch[2] == '>');
default:
return ch[0] == '>' || (ch[0] == '/' && ch[1] == '>');
}
}
 
static const char * _alnum =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"1234567890"
"_.-:";
 
static int isxmlalnum(const char ch)
{
return strchr(_alnum, ch) ? 1 : 0;
}
 
static int cxml_handler_parse_tag(cxml_handler_t * h, cxml_tag_t * * const tag, char * * ptr)
{
char *b, *e;
char * tend = NULL;
char * aend = NULL;
char * vend = NULL;
cxml_tag_t * t = NULL;
cxml_attr_t * a = NULL;
uint type = CXML_TAG_OPEN;
 
b = (*ptr)+1;
if (b[0] == '!' && b[1] == '-' && b[2] == '-'){
b+=3;
e = b;
while(*b && !istagend(type, b))b++;
if(*b == 0) ASSERT_GOTO(err);
tend = b;
t=cxml_tag_new(h, CXML_TAG_COMMENT, e);
}else{
if(*b == '/'){
type = CXML_TAG_CLOSE;
b++;
} else if (*b == '?'){
type = CXML_TAG_SYSTEM;
b++;
} else {
type = CXML_TAG_OPEN;
}
if(0==*b || isspace(*b)) goto err;
e = b;
do{
if(isspace(*e))break;
if(0==*e) ASSERT_GOTO(err);
if(istagend(type, e))break;
e++;
}while(1);
if(e>b){
/* b:e - tag name */
tend = e;
while(*e && isspace(*e))e++;
t = cxml_tag_new(h, type, b);
b = e;
/* parse attributes */
while(*b && !istagend(type, b)){
while(*b && isspace(*b))b++;
e = b;
while(isxmlalnum(*e))e++;
if(e>b){
if(aend) *aend = 0;
aend = e;
while(*e && isspace(*e))e++;
a = cxml_attr_new(h, b);
if(*e == '='){
e++;
b = e;
while(*b && isspace(*b))b++;
if(*b == '"'){
b++;
e = strchr(b, '"');
if(!e) ASSERT_GOTO(err);
*e = 0;
if(0 > cxml_text_decode(h, b, e-b))
ASSERT_GOTO(err);
e++;
a->value = b;
}else{
e = b;
while(*e && !istagend(type, e) && !isspace(*e))e++;
if(0==*e)ASSERT_GOTO(err);
if(vend){
*vend = 0;
if(0 > cxml_text_decode(h, (char*)t->attributes->value, vend - t->attributes->value))
ASSERT_GOTO(err);
}
vend = e;
a->value = b;
}
}else{
/* EXTENSION */
/* boolean values */
a->value = "true";
vend = NULL;
}
a->next = t->attributes;
t->attributes = a;
a = NULL;
}
b = e;
}
}
}
while(*b && *b != '>') b++;
if(*(b-1) == '/' && t->type == CXML_TAG_OPEN){
t->type = CXML_TAG_AUTOCLOSE;
}
*tend = 0;
if(aend) *aend = 0;
if(vend){
*vend = 0;
if(0 > cxml_text_decode(h, (char*)t->attributes->value, vend - t->attributes->value))
ASSERT_GOTO(err);
}
*tag = t;
*ptr = b;
return 0;
err:
if(a){
cxml_attr_free(h, a);
}
if(t){
cxml_tag_free(h, t);
}
return -1;
}
 
static int cxml_equal_name(const char * p1, const char * p2)
{
int rc;
 
if(0 == *p1)
return 1;
 
do{
if(!isxmlalnum(*p2)){
rc = -1;
break;
}
rc = *p1 - *p2;
p1++;
p2++;
}while(rc == 0 && *p1);
if(rc == 0 && !isxmlalnum(*p2)){
return 1;
}
return 0;
}
 
static int cxml_handler_parse_buffer(void * const ph, char* const text)
{
int ret = 0;
char *b, *e;
cxml_handler_t * h = (cxml_handler_t*)ph;
b = text;
 
/* strip leading spaces */
while(*b && isspace(*b))b++;
e = b;
while(*e){
cxml_tag_t * tag = NULL;
char * q;
if(*e == '<'){
q=e;
if(h->WaitTag){
if(e[1] != '/' || !cxml_equal_name(h->WaitTag, e+2)){
e++;
continue;
}
h->WaitTag = NULL;
}
ret = cxml_handler_parse_tag(h, &tag, &e);
if(ret < 0 ){
return ret;
}
if(q>b){
/* text exist */
if(h->Class->text){
ret = cxml_handler_post_text(h, b, q);
if(ret < 0) ASSERT_RETURN(-1);
}
}
ret = 0;
switch(tag->type){
case CXML_TAG_AUTOCLOSE: /* autoclose */
ret = cxml_call_handler(h->Class->tag_begin, h, tag);
if(ret < 0) break;
case CXML_TAG_CLOSE: /* close */
ret = cxml_call_handler(h->Class->tag_end, h, tag);
// if(h->Class->tag_end){
// ret = h->Class->tag_end(h, tag);
// }
break;
case CXML_TAG_SYSTEM:
if(cxml_tag_is(tag, "xml")){
/* fill in version and encoding */
h->Version = cxml_tag_attr_value(tag, "version");
h->Encoding = cxml_tag_attr_value(tag, "encoding");
}
case CXML_TAG_OPEN : /* opening */
default:
ret = cxml_call_handler(h->Class->tag_begin, h, tag);
// if(h->Class->tag_begin){
// ret = h->Class->tag_begin(h, tag);
// }
break;
};
if(ret<0) cxml_assert();
cxml_tag_free(h, tag);
if(ret<0) ASSERT_RETURN(-1);
b=e+1;
}
e++;
}
if(e > b){
ret = cxml_handler_post_text(h, b, e);
}
return ret;
}
 
int cxml_handler_parse(void * const ph, char* const text)
{
int ret = 0;
cxml_handler_t * h = (cxml_handler_t*)ph;
if(h->Class->doc_begin){
ret = h->Class->doc_begin((cxml_handler_t*) h, 0);
}
 
if(ret >= 0){
ret = cxml_handler_parse_buffer(ph, text);
}
 
if(h->Class->doc_end){
ret = h->Class->doc_end((cxml_handler_t*) h, ret);
}
return ret;
}
 
int cxml_handler_parse_stream(void * const ph, FILE * f)
{
char *buf;
long fsize;
size_t rsize;
int ret = -1;
 
cxml_handler_t * h = (cxml_handler_t*)ph;
 
if(fseek(f, 0, SEEK_END)){
perror("fseek");
return -1;
}
if( 0 > (fsize = ftell(f))){
perror("ftell");
return -1;
}
if(fsize > 0xFFFF){
return -1;
}
if(fseek(f, 0, SEEK_SET)){
perror("fseek");
return -1;
}
buf = cxml_alloc(h, fsize+1);
if(NULL == buf){
return -1;
}
 
rsize = fread(buf, 1, fsize, f);
if(rsize == (size_t)fsize){
ret = 0;
if(h->Class->doc_begin){
ret = h->Class->doc_begin((cxml_handler_t*) h, 0);
}
buf[rsize] = 0;
if(ret >= 0){
ret = cxml_handler_parse_buffer(ph, buf);
}
if(h->Class->doc_end){
ret = h->Class->doc_end((cxml_handler_t*) h, ret);
}
}
cxml_free(h, buf);
ASSERT_RETURN(ret);
}
 
int cxml_handler_parse_file(void * const ph, const char * file)
{
FILE * f;
int ret = -1;
f = fopen(file, "r");
if(f){
cxml_handler_t * h = (cxml_handler_t*)ph;
h->File = file;
ret = cxml_handler_parse_stream(ph, f);
fclose(f);
}
return ret;
}
 
void * cxml_alloc(void * const p, unsigned int size)
{
void * ptr;
cxml_handler_t * h = (cxml_handler_t*)p;
if(h->Class->alloc){
ptr = h->Class->alloc(size);
}else{
ptr = malloc(size);
}
return ptr;
}
 
void cxml_free(void * const p, void const * ptr)
{
cxml_handler_t * h = (cxml_handler_t*)p;
if(h->Class->free){
h->Class->free((void*)ptr);
}else{
free((void*)ptr);
}
}
 
#ifdef DEBUG
int cxml_checkassert(int rc)
{
if(rc == -1){
cxml_assert();
}
return rc;
}
void cxml_assert(void)
{
raise(SIGINT);
}
#endif
/trunk/tools/itscertgen/cxml/cxml.h
0,0 → 1,165
#ifndef cxml_h
#define cxml_h
 
#ifdef __cplusplus
extern "C" {
#endif
 
#if defined(_DEBUG) && !defined(DEBUG)
#define DEBUG _DEBUG
#endif
 
typedef struct cxml_attr_t cxml_attr_t;
typedef struct cxml_tag_t cxml_tag_t;
struct cxml_attr_t
{
cxml_attr_t * next;
const char * name;
const char * value;
};
 
typedef enum {
CXML_TAG_SYSTEM = 0,
CXML_TAG_OPEN,
CXML_TAG_CLOSE,
CXML_TAG_AUTOCLOSE,
CXML_TAG_COMMENT,
/* internal tag types */
CXML_TAG_CDATA = 8,
CXML_TAG_ENTITY = 12,
}cxml_tag_type;
 
#define cxml_tag_is_open(tag) (tag->type & CXML_TAG_OPEN)
#define cxml_tag_is_close(tag) (tag->type & CXML_TAG_CLOSE)
 
struct cxml_tag_t
{
int ucount;
cxml_tag_type type;
const char * nspace;
const char * name;
cxml_attr_t * attributes;
};
 
typedef struct cxml_handler_t cxml_handler_t;
typedef struct cxml_handler_class cxml_handler_class;
typedef struct cxml_entity_t cxml_entity_t;
 
typedef int (cxml_doc_f)(cxml_handler_t* const h, int rc);
typedef int (cxml_tag_f)(cxml_handler_t* const h, cxml_tag_t * const tag);
typedef int (cxml_text_f)(cxml_handler_t* const h, char * const text, int length);
 
typedef void * (cxml_alloc_f)(unsigned int);
typedef void (cxml_free_f)(void *);
 
struct cxml_handler_t
{
const cxml_handler_class * Class;
const char * File;
const char * Version;
const char * Encoding;
const char * WaitTag;
cxml_entity_t * Entities;
};
 
struct cxml_handler_class
{
unsigned int size;
cxml_doc_f * doc_begin;
cxml_doc_f * doc_end;
cxml_tag_f * tag_begin;
cxml_tag_f * tag_end;
cxml_text_f * text;
 
/* Allocation halpers.
* Can be NULL to use default ones */
cxml_alloc_f * tag_alloc;
cxml_free_f * tag_free;
cxml_alloc_f * alloc;
cxml_free_f * free;
};
 
struct cxml_entity_t
{
cxml_entity_t * next;
int nlen;
const char * name;
int vlen;
char value[];
};
 
void cxml_handler_init(void * const h, const cxml_handler_class * const Class);
void * cxml_handler_new(const cxml_handler_class * const Class);
void cxml_handler_delete(void * const h);
void cxml_handler_close(void * const h);
 
int cxml_handler_parse(void * const h, char* const text);
int cxml_handler_parse_file(void * const h, const char * file);
#if defined(SEEK_SET) || defined (_FILE_DEFINED)
#define _CXML_HANDLER_PARSE_STREAM_DEFINED
int cxml_handler_parse_stream(void * const h, FILE * f);
#endif
 
/* Internal functions for tags manipulations */
cxml_tag_t * cxml_tag_new(void * const h, const cxml_tag_type type, const char * const name);
cxml_tag_t * cxml_tag_use(cxml_tag_t * const tag);
void cxml_tag_free(void * const h, cxml_tag_t * const tag);
void cxml_wait_for_close(void * const p, cxml_tag_t * const tag);
 
cxml_attr_t * cxml_attr_new(void * const h, const char * const name);
void cxml_attr_free(void * const h, cxml_attr_t * const a);
 
int cxml_tag_is(const cxml_tag_t * const tag, const char * const tagname);
int cxml_tag_has_attr(cxml_tag_t * const tag, const char * const key);
const char * cxml_tag_attr_value(cxml_tag_t * const tag, const char * const key);
int cxml_tag_attr_int(cxml_tag_t * const tag, const char * const key);
unsigned int cxml_tag_attr_uint(cxml_tag_t * const tag, const char * const key);
int cxml_tag_attr_boolean(cxml_tag_t * const tag, const char * const key);
 
int cxml_handler_add_entity(void * const h, const char * const name, char * const value, const int value_len);
int cxml_handler_add_entity_from_tag(void * const h, cxml_tag_t * const tag);
 
int cxml_text_decode(void * const handler, char * const src, int const srclen);
int cxml_text_encode(void * const handler, char * * const p_dst,
const char * const src, int const srclen);
 
/** Utility function to process basic DCMI encoding */
int cxml_to_dcmi(char ** const pdst, const char * const src, int const len);
 
/** XML states and tag handlers support */
typedef struct cxml_taghandler_t cxml_taghandler_t;
 
struct cxml_taghandler_t
{
const char * tagname;
cxml_tag_f * on_tag;
cxml_text_f * on_text;
const cxml_taghandler_t * childs;
};
#define CXML_HDEFAULT ((const char *)1)
#define CXML_HCOMMENT ((const char *)2)
#define CXML_HSYSTEM ((const char *)3)
 
void * cxml_st_handler_new(const cxml_handler_class * const Class,
const cxml_taghandler_t * const Handlers);
void cxml_st_handler_delete(void * const h);
 
const cxml_tag_t * cxml_st_current_tag(void * const h);
 
void * cxml_alloc(void * const h, unsigned int size);
void cxml_free(void * const h, void const * ptr);
 
#ifdef DEBUG
#define ASSERT_RETURN(RC) do {return cxml_checkassert(RC);}while(0)
#define ASSERT_GOTO(LABEL) do {cxml_assert(); goto LABEL; }while(0)
void cxml_assert(void);
int cxml_checkassert(int rc);
#else
#define ASSERT_RETURN(RC) return RC
#define ASSERT_GOTO(LABEL) goto LABEL
#endif
#endif
 
#ifdef __cplusplus
}
#endif
/trunk/tools/itscertgen/cxml/cxml.vcxproj
0,0 → 1,90
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="cxml.c" />
<ClCompile Include="cxmlst.c" />
<ClCompile Include="cxml_dcmi.c" />
<ClCompile Include="cxml_decode.c" />
<ClCompile Include="cxml_encode.c" />
<ClCompile Include="cxml_entity.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="cxml.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>cxml</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)msvc\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)msvc\$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
/trunk/tools/itscertgen/cxml/cxml_dcmi.c
0,0 → 1,143
#include "cxml.h"
#include <string.h>
#include <stdlib.h>
#include <errno.h>
 
static const char * _dcmi_chars = "&<>'\"";
struct dcmi_tag{
const char * str;
int len;
};
static const struct dcmi_tag _dcmi_strs[] = {
{"&amp;", 5},
{"&lt;", 4},
{"&gt;", 4},
{"&apos;", 6},
{"&quot;", 6},
};
#define dcmi_tag_count (sizeof(_dcmi_strs)/sizeof(_dcmi_strs[0]))
 
int cxml_to_dcmi (char ** const pdst, const char * const src, int const src_length)
{
const char *s, *se;
char *d, *dst;
int slen;
int len, alen;
 
if(src_length > 0) slen = src_length;
else slen = strlen(src);
 
len = slen;
alen = (slen | 0xF) + 1;
dst = malloc(alen);
 
s = src;
se = s + slen;
d = dst;
 
while(s < se){
char * n;
n = strchr(_dcmi_chars, *s);
if(n){
const struct dcmi_tag * to;
to = &_dcmi_strs[n-_dcmi_chars];
len += to->len - 1;
if(len > alen){
alen = (len | 0xF) + 1;
n = realloc(dst, alen);
d = n + (d-dst);
dst = n;
}
memcpy(d, to->str, to->len);
d += to->len;
}else{
*(d++) = *s;
}
s++;
}
*pdst = dst;
return len;
}
 
int to_dcmi(char ** s)
{
int count = 0;
char *b, *p, *e;
int len, alen;
 
b = p = *s;
len = strlen(b);
e = b + len;
alen=len+2;
 
while(p < e){
char * n;
n = strchr(_dcmi_chars, *p);
if(n){
const struct dcmi_tag * to;
to = &_dcmi_strs[n-_dcmi_chars];
if(len + (to->len) > alen){
int l = len + to->len - 1;
alen = (l & 0xF) + 1;
n = realloc(b, alen);
p = n + (p-b);
b = n;
}
memmove(p + to->len, p+1, e-p);
memcpy(p, to->str, to->len);
e += to->len - 1;
p += to->len;
count++;
}else{
p++;
}
}
*s = b;
return count;
}
 
int cxml_from_dcmi(char * const s, int len)
{
char * p = s;
if(len <= 0){
len = strlen(p);
}
 
while(1){
unsigned int i;
char * e;
p = strchr(p, '&');
if(!p) break;
if(p[1] == '#'){
unsigned long val;
errno = 0;
if(p[2] == 'x'){ /* hexadecimal value */
val = strtoul(p+3, &e, 16);
}else{ /* decimal value */
val = strtoul(p+3, &e, 10);
}
if(errno || val > 0xFFFF || *e != ';'){
return -1;
}
if(val > 0xFF){
*p++ = (char)(val>>8);
}
*p++ = val&0xFF;
e++;
}else{
for(i=0; i<dcmi_tag_count; i++){
if(0 == strncmp(_dcmi_strs[i].str, p, _dcmi_strs[i].len)){
e = p + _dcmi_strs[i].len;
*p++ = _dcmi_chars[i];
break;
}
}
if(i == dcmi_tag_count){
return -1;
}
}
memmove(p, e, len-(s-e)+1);
len -= (e-p);
}
return len;
}
/trunk/tools/itscertgen/cxml/Makefile
0,0 → 1,16
BUILDROOT = ..
PROJECT = cxml
DEBUG = yes
testdir = tests
 
alibs = $(PROJECT)
solibs = $(PROJECT)
 
sources := cxml.c cxml_dcmi.c cxml_decode.c cxml_encode.c cxml_entity.c cxmlst.c
headers := cxml.h
tests := parser.c parser_st.c
distfiles := tests/test.xml tests/test_st.xml
 
cflags-POSIX := -fPIC
 
include ../common.mk
/trunk/tools/itscertgen/cxml/cxml_decode.c
0,0 → 1,74
#include "cxml.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int cxml_text_decode(void * const handler, char * const src, int const srclen)
{
const char * s = src;
const char * send = src + srclen;
char * d = src;
char * dend = d + srclen;
char * e;
cxml_entity_t * c;
cxml_handler_t * h = (cxml_handler_t *)handler;
 
while(s != send){
if(d>=dend)return -1;
if(*s != '&'){
if(d != s){
*d = *s;
}
d++; s++;
continue;
}
s++;
if(*s == '#'){
unsigned int value;
s++;
errno = 0;
if(*s == 'x' || *s == 'X'){
/* hexadecimal symbol representation */
s++;
value = strtoul(s, &e, 16);
}else if(*s >= '0' && *s <= '9'){
/* decimal symbol representation */
value = strtoul(s, &e, 10);
}else{
ASSERT_RETURN(-1);
}
if(errno != 0 || *e != ';'){
ASSERT_RETURN(-1);
}
if(value > 0xFFFFFF)
*(d++) = (char)((value>>24)&0xFF);
if(value > 0xFFFF)
*(d++) = (char)((value>>16)&0xFF);
if(value > 0xFF)
*(d++) = (char)((value>>8)&0xFF);
*(d++) = value&0xFF;
s = e+1;
continue;
}
 
c = h->Entities;
while(c){
if(c->nlen < (send-s) && s[c->nlen] == ';'){
if(0 == memcmp(c->name, s, c->nlen)){
break;
}
}
c = c->next;
}
if(c == NULL){
ASSERT_RETURN(-1);
}
if(d + c->vlen > s + (c->nlen + 1)){
ASSERT_RETURN(-1);
}
memcpy(d, c->value, c->vlen);
d += c->vlen;
s += c->nlen + 1;
}
*d = 0;
return d - src;
}
/trunk/tools/itscertgen/cxml/cxml_encode.c
0,0 → 1,98
#include "cxml.h"
#include <stdlib.h>
#include <string.h>
 
static const char _hex_digits[] = "0123456789ABCDEF";
 
static int _prepare(void * const handler,
char * * const p_beg,
char * * const p_cur,
char * * const p_end)
{
char * beg, *cur, *end;
beg = *p_beg;
cur = *p_cur;
end = *p_cur;
 
char * p = cxml_alloc(handler, 17 + (end-beg));
if(p){
if(cur>beg){
memcpy(p, beg, cur-beg);
}
cxml_free(handler, beg);
*p_cur = p + (cur-beg);
*p_end = p + 16 + (end-beg);
*p_beg = p;
return (end-beg) + 16;
}
cxml_free(handler, beg);
return -1;
}
 
int cxml_text_encode(void * const handler, char * * const p_dst,
const char * const src, int const len)
{
cxml_handler_t * h = (cxml_handler_t *)handler;
int srclen;
if(len <= 0 ) srclen = strlen(src);
else srclen = len;
 
char * db = cxml_alloc(handler, srclen+1);
char * de = db + srclen;
const char * s = src;
const char * se = src + srclen;
char * d = db;
 
while(s < se){
/* search for entities */
cxml_entity_t *c, *fc = NULL;
c = h->Entities;
while(c){
if((se-s) >= c->vlen){
if(0 == memcmp(s, c->value, c->vlen)){
if(fc == NULL || fc->vlen < c->vlen){
fc = c;
}
}
}
c = c->next;
}
if(fc){
while(d + fc->nlen + 2 > de){
if(-1 == _prepare(handler, &db, &d, &de)){
return -1;
}
}
* d ++ = '&';
memcpy(d, fc->name, fc->nlen); d+=fc->nlen;
* d ++ = ';';
s += fc->vlen;
}else{
/* check for supported symbol range */
unsigned char ch = *s;
if(ch < ' ' && ch != '\t' && ch != '\n' && ch != '\r'){
if(d + 5 > de){
if(-1 == _prepare(handler, &db, &d, &de)){
return -1;
}
}
* d ++ = '&';
* d ++ = '#';
* d ++ = _hex_digits[(ch >> 4)];
* d ++ = _hex_digits[(ch &0xF)];
* d ++ = ';';
}else{
if(d >= de){
if(-1 == _prepare(handler, &db, &d, &de)){
return -1;
}
}
* d ++ = ch;
}
s++;
}
}
*d = 0;
*p_dst = db;
return d-db;
}
/trunk/tools/itscertgen/cxml/cxml_entity.c
0,0 → 1,91
#include "cxml.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
 
static cxml_entity_t * cxml_entity_new(void * const p, const char * const name, char * const value, const int value_len)
{
cxml_entity_t * e;
 
e = cxml_alloc(p, sizeof(cxml_entity_t) + value_len + 1);
e->next = NULL;
e->name = name;
e->nlen = strlen(name);
if(value && value_len) {
memcpy(e->value, value, value_len);
e->value[value_len] = 0;
e->vlen = cxml_text_decode(p, e->value, value_len);
if(e->vlen < 0){
cxml_free(p, e);
return NULL;
}
e->value[e->vlen] = 0;
}
return e;
}
 
static void cxml_entity_append(cxml_handler_t * const h, cxml_entity_t * const e)
{
cxml_entity_t * c = h->Entities;
cxml_entity_t * p = NULL;
int found = 0;
while(c){
if(!found && 0 == strcmp(c->name, e->name)){
/* remove old one */
if(p){
p->next = c->next;
cxml_free(h, c);
c = p->next;
}else{
h->Entities = c->next;
cxml_free(h, c);
c = h->Entities;
}
found = 1;
}
p = c;
c = c->next;
}
if(p){
p->next = e;
}else{
h->Entities = e;
}
}
 
int cxml_handler_add_entity(void * const p, const char * const name, char * const value, const int value_len)
{
cxml_entity_t * e = cxml_entity_new(p, name, value, value_len);
if(e){
cxml_entity_append(p, e);
return 0;
}
return -1;
}
 
void cxml_handler_add_default_entities(void * const h)
{
cxml_handler_add_entity(h, "gt", "&#x3E;", 6);
cxml_handler_add_entity(h, "lt", "&#x3C;", 6);
cxml_handler_add_entity(h, "amp", "&#x26;", 6);
cxml_handler_add_entity(h, "quot", "&#x22;", 6);
cxml_handler_add_entity(h, "apos", "&#x27;", 6);
}
 
int cxml_handler_add_entity_from_tag(void * const h, cxml_tag_t * const tag)
{
char * v = NULL;
int vlen = 0;
 
if(tag->type != CXML_TAG_ENTITY){
return -1;
}
if(tag->attributes){
v = (char*)tag->attributes->value;
if(v){
vlen = strlen(v);
}
}
return cxml_handler_add_entity(h, tag->name, v, vlen);
}
/trunk/tools/itscertgen/cxml/cxmlst.c
0,0 → 1,196
#include "cxml.h"
#include <stdlib.h>
#include <string.h>
 
#if __SIZEOF_POINTER__ == __SIZEOF_LONG__
typedef unsigned long intpointer_t;
#elif __SIZEOF_POINTER__ == __SIZEOF_LONG_LONG__
typedef unsigned long long intpointer_t;
#else
typedef unsigned int intpointer_t;
#endif
 
typedef struct cxmlst_tag_t cxmlst_tag_t;
 
struct cxmlst_tag_t
{
cxml_tag_t tag;
cxmlst_tag_t * parent;
cxml_tag_f * on_close;
cxml_text_f * p_text;
const cxml_taghandler_t * subhandlers;
};
 
typedef struct cxmlst_handler_t
{
const cxml_taghandler_t * handlers;
cxmlst_tag_t * stack;
cxml_handler_t h;
}cxmlst_handler_t;
 
static cxmlst_handler_t * to_cxmlst_handler(void * const p)
{
char * ptr = p;
ptr -= sizeof(cxmlst_handler_t)-sizeof(cxml_handler_t);
return (cxmlst_handler_t *)ptr;
}
/*
#define to_cxmlst_handler(p) \
((cxmlst_handler_t*) \
((char*)p)-(sizeof(cxmlst_handler_t)-sizeof(cxml_handler_t)))
*/
static int _cxmlst_tag_begin(cxml_handler_t* const h, cxml_tag_t * const tag);
static int _cxmlst_tag_end (cxml_handler_t* const h, cxml_tag_t * const tag);
 
static void * _cxmlst_tag_alloc(unsigned int size)
{
if(size < sizeof(cxmlst_tag_t))
size = sizeof(cxmlst_tag_t);
return malloc(size);
}
static void _cxmlst_tag_free (void * p)
{
free((cxmlst_tag_t*)p);
}
 
void * cxml_st_handler_new(const cxml_handler_class * const Class,
const cxml_taghandler_t * const Handlers)
{
cxmlst_handler_t * h;
cxml_handler_class * cl;
size_t hsize = Class->size + sizeof(cxmlst_handler_t) - sizeof(cxml_handler_t);
if(hsize < sizeof(cxmlst_handler_t)) hsize = sizeof(cxmlst_handler_t);
 
cl = malloc(sizeof(cxml_handler_class));
memcpy(cl, Class, sizeof(cxml_handler_class));
cl->tag_begin = _cxmlst_tag_begin;
cl->tag_end = _cxmlst_tag_end;
cl->tag_alloc = _cxmlst_tag_alloc;
cl->tag_free = _cxmlst_tag_free;
 
h = malloc(hsize);
cxml_handler_init(&h->h, cl);
h->handlers = Handlers;
h->stack = NULL;
return &h->h;
}
 
void cxml_st_handler_delete(void * const p)
{
cxmlst_handler_t * h = to_cxmlst_handler(p);
cxml_handler_class * cl = (cxml_handler_class *)h->h.Class;
while(h->stack){
cxmlst_tag_t * t = h->stack;
h->stack = t->parent;
cxml_tag_free(p, &t->tag);
}
cxml_handler_close(p);
free(h);
free(cl);
}
 
static int _cxmlst_tag_begin(cxml_handler_t* const p, cxml_tag_t * const tag)
{
int rc = -1;
cxmlst_handler_t * h = to_cxmlst_handler(p);
const cxml_taghandler_t * i;
const cxml_taghandler_t * found = NULL;
 
if(NULL == h->handlers){
return -1;
}
 
 
i=h->handlers;
for(;i->tagname; i++){
intpointer_t nll = (intpointer_t)i->tagname;
if(nll <= 10){
if(i->tagname == CXML_HDEFAULT){
found = i;
}else if(i->tagname == CXML_HCOMMENT){
if(tag->type == CXML_TAG_COMMENT) found = i;
}else if(i->tagname == CXML_HSYSTEM){
if(tag->type == CXML_TAG_SYSTEM) found = i;
}else{
return -1;
}
}else{
if(tag->type != CXML_TAG_COMMENT){
if(0==strcmp(tag->name, i->tagname)){
found = i;
break;
}
}
}
}
 
if(found) {
rc = found->on_tag ? found->on_tag(&h->h, tag) : 0;
 
if( rc >= 0 ){
/* store tag in the stack */
cxmlst_tag_t * tst = (cxmlst_tag_t *)tag;
cxml_handler_class * cl = (cxml_handler_class *)h->h.Class;
cxml_tag_use(tag);
tst->subhandlers = h->handlers;
tst->parent = h->stack;
tst->p_text = cl->text;
h->stack = tst;
 
/* update class fields */
/* check if this tag have a non-xml body */
if(NULL == found->childs &&
tag->type == CXML_TAG_OPEN){
cxml_wait_for_close(&h->h, tag);
}
h->handlers = found->childs;
tst->on_close = found->on_tag;
cl->text = found->on_text;
}
}else{
if(tag->type == (tag->type & ~0x3)){
rc = 0;
}
}
return rc;
}
 
static int _cxmlst_tag_end (cxml_handler_t* const p, cxml_tag_t * const tag)
{
int rc;
cxml_handler_class * cl = (cxml_handler_class *)p->Class;
cxmlst_handler_t * h = to_cxmlst_handler(p);
cxmlst_tag_t *parent, *cur;
 
/* check for empty stack */
if(h->stack == NULL)
return -1;
 
cur = h->stack;
parent = cur->parent;
 
/* check the stack top for the same tag */
if(strcmp(tag->name, cur->tag.name)){
return -1;
}
 
if(tag->type == CXML_TAG_AUTOCLOSE){
tag->type = CXML_TAG_CLOSE;
}
 
h->handlers = cur->subhandlers;
cl->text = cur->p_text;
if(cur->on_close)
rc = cur->on_close(p, tag);
else
rc = 0;
h->stack = parent;
cxml_tag_free(p, &cur->tag);
return rc;
}
 
const cxml_tag_t * cxml_st_current_tag (void * const p)
{
cxmlst_handler_t * h = to_cxmlst_handler(p);
return (cxml_tag_t*)h->stack;
}
/trunk/tools/itscertgen/cxml/tests/parser.c
0,0 → 1,113
#include "../cxml.h"
#include <stdio.h>
#include <stdlib.h>
 
static unsigned int deep = 0;
static int cxml_Test_Begin(cxml_handler_t* const h, int dummy)
{
printf("Document begin\n");
deep = 0;
return 0;
}
 
static int cxml_Test_End(cxml_handler_t* const h, int rc)
{
printf("Document end, rc=%d\n", rc);
return 0;
}
 
static void print_tag(cxml_handler_t* const h, const cxml_tag_t * const tag)
{
cxml_attr_t * a;
printf("<");
switch(tag->type){
case CXML_TAG_CLOSE:
printf("/");
break;
case CXML_TAG_SYSTEM:
printf("?");
break;
case CXML_TAG_COMMENT:
printf("--");
break;
default:
break;
};
printf("%s", tag->name);
 
a = tag->attributes;
while(a){
if(a->value){
char * v;
int ret = cxml_text_encode(h, &v, a->value, -1);
if(ret >= 0){
printf(" %s=\"%s\"", a->name, v);
cxml_free(h, v);
}
}else{
printf(" %s", a->name);
}
a = a->next;
}
switch(tag->type){
case CXML_TAG_AUTOCLOSE:
printf("/");
break;
case CXML_TAG_SYSTEM:
printf("?");
break;
case CXML_TAG_COMMENT:
printf("--");
break;
default:
break;
};
printf(">");
}
 
static int cxml_Test_Tag_Begin(cxml_handler_t* const h, cxml_tag_t * const tag)
{
print_tag(h, tag);
return 0;
}
 
static int cxml_Test_Tag_End(cxml_handler_t* const h, cxml_tag_t * const tag)
{
if(tag->type != CXML_TAG_AUTOCLOSE){
print_tag(h, tag);
}
return 0;
}
 
static int cxml_Test_Text(cxml_handler_t* const h, char * const text)
{
if(text){
char * ptr;
int ret = cxml_text_encode(h, &ptr, text, -1);
if(ret >= 0){
printf("%s", ptr);
cxml_free(h, ptr);
}
}
return 0;
}
 
static cxml_handler_class Class = {
sizeof(cxml_handler_t),
cxml_Test_Begin, cxml_Test_End,
cxml_Test_Tag_Begin, cxml_Test_Tag_End,
cxml_Test_Text
};
 
int main(int argc, char** argv)
{
int i;
cxml_handler_t * h;
h = cxml_handler_new(&Class);
for(i=1; i<argc; i++){
int rc = cxml_handler_parse_file(h, argv[i]);
printf("Parsing Done. rc=%d\n", rc);
}
cxml_handler_delete(h);
return 0;
}
/trunk/tools/itscertgen/cxml/tests/parser_st.c
0,0 → 1,168
#include "../cxml.h"
#include <stdio.h>
#include <stdlib.h>
 
static unsigned int deep = 0;
static int cxml_Doc_Begin(cxml_handler_t* const h, int rc)
{
printf("%s: Document begin\n", h->File);
deep = 0;
return 0;
}
 
static int cxml_Doc_End(cxml_handler_t* const h, int rc)
{
printf("%s: Document end, rc=%d\n", h->File, rc);
return rc;
}
 
static int root_tag1_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int root_tag2_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int root_tag3_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int root_unknown_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int root_system_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int tag1_tag_12_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int tag1_tag_13_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int tag1_unknown_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int tag2_tag23_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
static int tag2_root_handler(cxml_handler_t* const h, cxml_tag_t * const tag);
 
static int root_text (cxml_handler_t* const h, char * const text);
static int tag1_text (cxml_handler_t* const h, char * const text);
static int tag2_text (cxml_handler_t* const h, char * const text);
static int tag12_text (cxml_handler_t* const h, char * const text);
static int tag13_text (cxml_handler_t* const h, char * const text);
static int default_text (cxml_handler_t* const h, char * const text);
 
static cxml_handler_class Class = {
.size = sizeof(cxml_handler_t),
.doc_begin = cxml_Doc_Begin,
.doc_end = cxml_Doc_End,
};
 
static const cxml_taghandler_t h_tag1[];
static const cxml_taghandler_t h_tag2[];
 
static const cxml_taghandler_t h_root[] = {
{"tag1", root_tag1_handler, tag1_text, h_tag1 },
{"tag2", root_tag2_handler, tag2_text, h_tag2 },
{"tag3", root_tag3_handler, NULL, NULL },
{CXML_HSYSTEM, root_system_handler, NULL, NULL },
{CXML_HDEFAULT, root_unknown_handler, root_text, NULL },
{NULL, NULL, NULL, NULL}
};
 
static const cxml_taghandler_t h_tag1[] = {
{"tag12", tag1_tag_12_handler, tag12_text, h_tag2 },
{"tag13", tag1_tag_13_handler, tag13_text, NULL },
{CXML_HDEFAULT, tag1_unknown_handler, default_text, NULL },
{NULL, NULL, NULL, NULL}
};
 
static const cxml_taghandler_t h_tag2[] = {
{"tag23", tag2_tag23_handler, NULL, NULL },
{"root", tag2_root_handler, NULL, h_root },
{NULL, NULL, NULL, NULL}
};
 
int main(int argc, char** argv)
{
int i;
cxml_handler_t * h;
h = cxml_st_handler_new(&Class, h_root);
for(i=1; i<argc; i++){
cxml_handler_parse_file(h, argv[i]);
}
cxml_st_handler_delete(h);
return 0;
}
 
static const char* _tag_prefix[] = { "?", "", "/", "", "!--" };
static const char* _tag_suffix[] = { "?", "", "", "/", "--" };
 
static int _cxml_echo_tag(const char * func, cxml_tag_t * const tag)
{
printf("TAG : <%s%s%s> Handler:%s\n",
_tag_prefix[tag->type],
tag->name,
_tag_suffix[tag->type],
func);
return 0;
}
static int root_tag1_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int root_tag2_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int root_tag3_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int tag1_tag_12_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int tag1_tag_13_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int tag2_tag23_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int tag2_root_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int _cxml_echo_text(cxml_handler_t* const h, const char * func, char * const text)
{
const cxml_tag_t * tag = cxml_st_current_tag (h);
 
printf("TEXT: <%s%s%s> Handler:%s, Data={%s}\n",
_tag_prefix[tag->type],
tag->name,
_tag_suffix[tag->type],
func, text);
return 0;
}
 
static int default_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
 
static int root_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
static int tag1_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
static int tag2_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
static int tag12_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
static int tag13_text (cxml_handler_t* const h, char * const text)
{
return _cxml_echo_text(h, __func__, text);
}
static int root_unknown_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int root_system_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
static int tag1_unknown_handler(cxml_handler_t* const h, cxml_tag_t * const tag)
{
return _cxml_echo_tag(__func__, tag);
}
/trunk/tools/itscertgen/cxml/tests/test.xml
0,0 → 1,11
<?xml?>
<tag>
<tag/>
</tag>
<!-- COMMENT -->
text text
text text &#x22;quoted&quot;
<tag attr=value attr="value value" attr>
<tag attr = value attr = "value &amp;value&#38;" attr />
</tag>
<tag attr=value attr="value value" attr/>
/trunk/tools/itscertgen/cxml/tests/test_st.xml
0,0 → 1,28
<tag1>
<tag12/>
text tag1 1
<tag12/>
text tag1 2
<unknown1/>
<unknown2>
text unknown
<tag12>
text tag12
<tag23/>
</tag12>
</unknown2>
<tag13>
<all/> <these/> tags <is/> <a text>
</tag13>
</tag1>
 
<tag2>
<root>
text root
<tag12/>
</root>
text tag2
</tag2>
 
/trunk/tools/itscertgen/ecc_api.h
0,0 → 1,45
#ifndef ecc_api_h
#define ecc_api_h
 
#ifdef __cplusplus
extern "C" {
#endif
 
 
int ecc_api_init();
int ecc_api_done();
 
typedef enum {
ecdsa_nistp256_with_sha256,
ecies_nistp256
}ecc_pk_algorithm;
 
typedef enum {
aes_128_ccm
}ecc_sym_algorithm;
 
typedef enum {
ecc_bin,
ecc_hex,
ecc_pem
}ecc_format;
 
void * ecc_api_key_gen (ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg);
void * ecc_api_key_init(ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg, const char* pkey);
void ecc_api_key_free(void*);
int ecc_api_key_private(void*, char* buf);
int ecc_api_key_public(void*, char* x, char* y);
int ecc_api_key_private_save(void*, const char* path, ecc_format format);
void * ecc_api_key_private_load(const char* path);
int ecc_api_key_public_save(void*, const char* path, ecc_format format);
void * ecc_api_key_public_load(const char* path);
 
#define sha256_hash_size 32
int sha256_calculate(char* hash, const char * ptr, int len);
 
int ecc_sign(void * key, const char * data, int length, char ** sig, int maxsize);
 
#ifdef __cplusplus
}
#endif
#endif
/trunk/tools/itscertgen/ecc_openssl.c
0,0 → 1,400
#include "ecc_api.h"
 
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/ec.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/ecdsa.h>
#include <string.h>
 
static const int _NIDS[] = {
NID_secp256k1,
NID_secp256k1
};
 
static EVP_PKEY_CTX *pctx[sizeof(_NIDS) / sizeof(_NIDS[0])] = { NULL };
static EVP_PKEY_CTX *kctx[sizeof(_NIDS) / sizeof(_NIDS[0])] = { NULL };
static EVP_PKEY *params[sizeof(_NIDS) / sizeof(_NIDS[0])] = { NULL };
 
int ecc_api_init()
{
int i;
int rc = -1;
for (i = 0; i < sizeof(_NIDS) / sizeof(_NIDS[0]); i++){
/* Create the context for generating the parameters */
pctx[i] = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
if (pctx[i]){
if (EVP_PKEY_paramgen_init(pctx[i])){
/* Set the paramgen parameters according to the type */
if (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx[i], _NIDS[i])){
/* Generate parameters */
if (EVP_PKEY_paramgen(pctx[i], &params[i])) {
/* Create context for the key generation */
kctx[i] = EVP_PKEY_CTX_new(params[i], NULL);
if (kctx[i]){
if (EVP_PKEY_keygen_init(kctx[i])){
rc = 0;
continue;
}
}
}
}
}
}
ERR_print_errors_fp(stderr);
if (kctx[i])EVP_PKEY_CTX_free(kctx[i]); kctx[i] = NULL;
if (params[i])EVP_PKEY_free(params[i]); params[i] = NULL;
if (pctx[i])EVP_PKEY_CTX_free(pctx[i]); pctx[i] = NULL;
}
return rc;
}
 
int ecc_api_done()
{
int i;
for (i = 0; i < sizeof(_NIDS) / sizeof(_NIDS[0]); i++){
if (kctx[i])EVP_PKEY_CTX_free(kctx[i]); kctx[i] = NULL;
if (params[i])EVP_PKEY_free(params[i]); params[i] = NULL;
if (pctx[i])EVP_PKEY_CTX_free(pctx[i]); pctx[i] = NULL;
}
return 0;
}
 
void * ecc_api_key_gen(ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg)
{
EVP_PKEY * key = NULL;
if (!EVP_PKEY_keygen(kctx[pk_alg], &key)){
ERR_print_errors_fp(stderr);
}
return (void*)key;
}
 
void * ecc_api_key_init(ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg, const char* pkey)
{
EVP_PKEY * key = NULL;
BIGNUM * bn = BN_new();
if (BN_bin2bn(pkey, 32, bn)){
EC_KEY * eckey = EC_KEY_new_by_curve_name(_NIDS[pk_alg]);
if (eckey){
if (EC_KEY_set_private_key(eckey, bn)){
EC_POINT * point;
const EC_GROUP * group;
group = EC_KEY_get0_group(eckey);
point = EC_POINT_new(group);
if (EC_POINT_mul(group, point, bn, NULL, NULL, NULL)){
EC_KEY_set_public_key(eckey, point);
key = EVP_PKEY_new();
EVP_PKEY_set1_EC_KEY(key, eckey);
eckey = NULL;
}
EC_POINT_free(point);
}
if (eckey){
EC_KEY_free(eckey);
}
}
}
BN_free(bn);
return (void*)key;
}
 
void ecc_api_key_free(void* key)
{
EVP_PKEY_free((EVP_PKEY*)key);
}
 
int ecc_api_key_private(void* key, char* buf)
{
int len = -1;
const EC_KEY * eckey;
eckey = EVP_PKEY_get1_EC_KEY((EVP_PKEY*)key);
if(eckey){
const BIGNUM * ecbn;
ecbn = EC_KEY_get0_private_key(eckey);
if(ecbn){
len = BN_num_bytes(ecbn);
if(buf){
BN_bn2bin(ecbn, (unsigned char*)buf);
}
}
}
return len;
}
int ecc_api_key_public(void* key, char * px, char * py)
{
const EC_KEY * eckey;
const EC_GROUP * ecgroup;
const EC_POINT * ecpoint;
BIGNUM x, y;
int bcount = -1;
eckey = EVP_PKEY_get1_EC_KEY(key);
ecgroup = EC_KEY_get0_group(eckey);
ecpoint = EC_KEY_get0_public_key(eckey);
 
//fill public key data
BN_init(&x); BN_init(&y);
if(EC_POINT_get_affine_coordinates_GFp(ecgroup, ecpoint, &x, &y, NULL)){
bcount = BN_num_bytes(&x);
if(px){
BN_bn2bin(&x, (unsigned char*)px);
}
 
bcount = BN_num_bytes(&y);
if(py){
BN_bn2bin(&x, (unsigned char*)py);
}
}
BN_clear_free(&x); BN_clear_free(&y);
return bcount;
}
 
static int _pass_cb(char *buf, int size, int rwflag, void *u)
{
fprintf(stderr, "Ask for a pass phrase");
return 0;
}
int ecc_api_key_private_save(void* key, const char* path, ecc_format format)
{
int rc = -1;
FILE * f = fopen(path, "wb");
if(f){
if (format == ecc_pem){
rc = PEM_write_PKCS8PrivateKey(f, key, NULL, NULL, 0, _pass_cb, NULL) ? 0 : -1;
if (rc < 0){
ERR_print_errors_fp(stderr);
}
}
else{
const EC_KEY * eckey;
eckey = EVP_PKEY_get1_EC_KEY((EVP_PKEY*)key);
if (eckey){
const BIGNUM * ecbn;
ecbn = EC_KEY_get0_private_key(eckey);
if (ecbn){
char * buf = NULL;
int len = BN_num_bytes(ecbn);
if (format == ecc_bin){
buf = (char *)OPENSSL_malloc(len);
BN_bn2bin(ecbn, buf);
rc = 0;
}
else if (format == ecc_hex){
buf = BN_bn2hex(ecbn);
len = strlen(buf);
rc = 0;
}
if (buf){
rc = (len == fwrite(buf, 1, len, f)) ? 0 : -1;
OPENSSL_free(buf);
}
}
}
}
fclose(f);
if (rc < 0){
ERR_print_errors_fp(stderr);
remove(path);
rc = -1;
}
}
else{
perror(path);
}
return rc;
}
 
void * ecc_api_key_private_load(const char* path)
{
EVP_PKEY * key = NULL;
FILE * f = fopen(path, "rb");
if (f){
key = PEM_read_PrivateKey(f, NULL, NULL, NULL);
if (key == NULL){
BIGNUM * bn = NULL;
fseek(f, 0, SEEK_END);
int len = ftell(f);
fseek(f, 0, SEEK_SET);
char * buf = OPENSSL_malloc(len + 1);
if (len == fread(buf, 1, len, f)){
buf[len] = 0;
// try hex first
if (len != BN_hex2bn(&bn, buf)){
if (bn){
BN_free(bn); bn = NULL;
}
bn = BN_bin2bn(buf, len, NULL);
}
}
OPENSSL_free(buf);
if (bn){
EC_KEY * eckey = EC_KEY_new_by_curve_name(_NIDS[0]);
if (eckey){
if (EC_KEY_set_private_key(eckey, bn)){
EC_POINT * point;
const EC_GROUP * group;
group = EC_KEY_get0_group(eckey);
point = EC_POINT_new(group);
if (EC_POINT_mul(group, point, bn, NULL, NULL, NULL)){
EC_KEY_set_public_key(eckey, point);
key = EVP_PKEY_new();
EVP_PKEY_assign_EC_KEY(key, eckey);
eckey = NULL;
}
EC_POINT_free(point);
}
if (eckey)EC_KEY_free(eckey);
}
BN_free(bn);
}
}
fclose(f);
}
return key;
}
 
int ecc_api_key_public_save(void* key , const char* path, ecc_format format)
{
int rc = -1;
FILE * f = fopen(path, "wb");
if (f){
const EC_KEY * eckey;
eckey = EVP_PKEY_get1_EC_KEY((EVP_PKEY*)key);
if (eckey){
if (format == ecc_pem){
rc = PEM_write_EC_PUBKEY(f, eckey) ? 0 : -1;
}
else{
size_t len;
char * buf = NULL;
const EC_POINT * point = EC_KEY_get0_public_key(eckey);
const EC_GROUP * group = EC_KEY_get0_group(eckey);
 
if (format == ecc_hex){
buf = EC_POINT_point2hex(group, point, POINT_CONVERSION_UNCOMPRESSED, NULL);
len = strlen(buf);
}
else if (format == ecc_bin){
len = EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
if (len > 0){
buf = OPENSSL_malloc(len + 1);
if (len != EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, buf, len, NULL)){
OPENSSL_free(buf); buf = NULL;
}
}
}
if (buf){
if (len == fwrite(buf, 1, len, f)){
rc = 0;
}
OPENSSL_free(buf); buf = NULL;
}
}
}
fclose(f);
if (rc < 0){
ERR_print_errors_fp(stderr);
remove(path);
}
}
else{
perror(path);
}
return rc;
}
 
void * ecc_api_key_public_load(const char* path, ecc_pk_algorithm pk_alg)
{
EVP_PKEY * key = NULL;
FILE * f = fopen(path, "rb");
if (f){
key = PEM_read_PUBKEY(f, &key, NULL, NULL);
if (key == NULL){
fseek(f, 0, SEEK_END);
int len = ftell(f);
fseek(f, 0, SEEK_SET);
char * buf = OPENSSL_malloc(len + 1);
if (len == fread(buf, 1, len, f)){
buf[len] = 0;
 
EC_KEY * eckey = EC_KEY_new_by_curve_name(_NIDS[pk_alg]);
if (eckey){
// try load hex
EC_POINT * point = NULL;
const EC_GROUP * group = EC_KEY_get0_group(eckey);
// try hex first
point = EC_POINT_hex2point(group, buf, NULL, NULL);
if (point == NULL){
// try oct
point = EC_POINT_oct2point(group, NULL, buf, len, NULL);
}
if (point){
EC_KEY_set_public_key(eckey, point);
EC_POINT_free(point);
key = EVP_PKEY_new();
EVP_PKEY_assign_EC_KEY(key, eckey);
eckey = NULL;
}
else{
EC_KEY_free(eckey);
}
}
}
OPENSSL_free(buf);
}
fclose(f);
}
return key;
}
 
int sha256_calculate(char* hash, const char * ptr, int len)
{
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, ptr, len);
SHA256_Final((unsigned char*)hash, &ctx);
return 0;
}
 
int ecc_sign(void * key, const char * data, int length, char ** psig, int maxsize)
{
EC_KEY * eckey;
unsigned char *sig = (unsigned char *)*psig;
 
if (65 <= maxsize){
eckey = EC_KEY_dup(EVP_PKEY_get1_EC_KEY(key));
if(eckey){
unsigned char hash[32];
ECDSA_SIG * ecdsa;
SHA256_CTX ctx;
BIGNUM *kinv = NULL;
BIGNUM *rp = NULL;
 
SHA256_Init(&ctx);
SHA256_Update(&ctx, data, length);
SHA256_Final(hash, &ctx);
 
if (ECDSA_sign_setup(eckey, NULL, &kinv, &rp)){
ecdsa = ECDSA_do_sign_ex(hash, 32, kinv, rp, eckey);
EC_KEY_free(eckey);
BN_clear_free(kinv);
BN_clear_free(rp);
if (ecdsa){
int bcount;
*(sig++) = 0; // x_coordinate_only
bcount = BN_num_bytes(ecdsa->r);
BN_bn2bin(ecdsa->r, sig);
sig += bcount;
bcount = BN_num_bytes(ecdsa->s);
BN_bn2bin(ecdsa->s, sig);
sig += bcount;
ECDSA_SIG_free(ecdsa);
*psig = (char*)sig;
return 0;
}
}
}
}
return -1;
}
/trunk/tools/itscertgen/itscertgen.vcxproj
0,0 → 1,107
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="applink.c" />
<ClCompile Include="certgen.c" />
<ClCompile Include="ecc_openssl.c" />
<ClCompile Include="ecc_openssl_ec.c">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="mkgmtime.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="ecc_api.h" />
<ClInclude Include="mkgmtime.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="cshared\cshared.vcxproj">
<Project>{d5918b85-fa45-4f75-9b50-c2d3e34aba17}</Project>
</ProjectReference>
<ProjectReference Include="cxml\cxml.vcxproj">
<Project>{cbfc4bfa-fe7e-45fb-ae2f-2608b7c0ad07}</Project>
</ProjectReference>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{17B446F1-6962-4B49-8A59-9584807F9024}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>itscertgen</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\msvc\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\msvc\$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>C:\OpenSSL-Win32\include</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>C:\OpenSSL-Win32\lib\VC\static</AdditionalLibraryDirectories>
<AdditionalDependencies>libeay32MDd.lib;ssleay32MDd.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
/trunk/tools/itscertgen/itscertgen.sln
0,0 → 1,38

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "itscertgen", "itscertgen.vcxproj", "{17B446F1-6962-4B49-8A59-9584807F9024}"
ProjectSection(ProjectDependencies) = postProject
{D5918B85-FA45-4F75-9B50-C2D3E34ABA17} = {D5918B85-FA45-4F75-9B50-C2D3E34ABA17}
{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07} = {CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cxml", "cxml\cxml.vcxproj", "{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cshared", "cshared\cshared.vcxproj", "{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{17B446F1-6962-4B49-8A59-9584807F9024}.Debug|Win32.ActiveCfg = Debug|Win32
{17B446F1-6962-4B49-8A59-9584807F9024}.Debug|Win32.Build.0 = Debug|Win32
{17B446F1-6962-4B49-8A59-9584807F9024}.Release|Win32.ActiveCfg = Release|Win32
{17B446F1-6962-4B49-8A59-9584807F9024}.Release|Win32.Build.0 = Release|Win32
{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}.Debug|Win32.ActiveCfg = Debug|Win32
{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}.Debug|Win32.Build.0 = Debug|Win32
{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}.Release|Win32.ActiveCfg = Release|Win32
{CBFC4BFA-FE7E-45FB-AE2F-2608B7C0AD07}.Release|Win32.Build.0 = Release|Win32
{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}.Debug|Win32.ActiveCfg = Debug|Win32
{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}.Debug|Win32.Build.0 = Debug|Win32
{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}.Release|Win32.ActiveCfg = Release|Win32
{D5918B85-FA45-4F75-9B50-C2D3E34ABA17}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
/trunk/tools/itscertgen/Makefile
0,0 → 1,8
BUILDROOT = .
PROJECT = kgen
DEBUG = yes
bins = certgen
sources := certgen.c ecc_openssl.c mkgmtime.c
sources-WIN32 := applink.c
packages += openssl cxml cshared
include common.mk
/trunk/tools/itscertgen/applink.c
0,0 → 1,94
#define APPLINK_STDIN 1
#define APPLINK_STDOUT 2
#define APPLINK_STDERR 3
#define APPLINK_FPRINTF 4
#define APPLINK_FGETS 5
#define APPLINK_FREAD 6
#define APPLINK_FWRITE 7
#define APPLINK_FSETMOD 8
#define APPLINK_FEOF 9
#define APPLINK_FCLOSE 10 /* should not be used */
 
#define APPLINK_FOPEN 11 /* solely for completeness */
#define APPLINK_FSEEK 12
#define APPLINK_FTELL 13
#define APPLINK_FFLUSH 14
#define APPLINK_FERROR 15
#define APPLINK_CLEARERR 16
#define APPLINK_FILENO 17 /* to be used with below */
 
#define APPLINK_OPEN 18 /* formally can't be used, as flags can vary */
#define APPLINK_READ 19
#define APPLINK_WRITE 20
#define APPLINK_LSEEK 21
#define APPLINK_CLOSE 22
#define APPLINK_MAX 22 /* always same as last macro */
 
#ifndef APPMACROS_ONLY
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
 
static void *app_stdin(void) { return stdin; }
static void *app_stdout(void) { return stdout; }
static void *app_stderr(void) { return stderr; }
static int app_feof(FILE *fp) { return feof(fp); }
static int app_ferror(FILE *fp) { return ferror(fp); }
static void app_clearerr(FILE *fp) { clearerr(fp); }
static int app_fileno(FILE *fp) { return _fileno(fp); }
static int app_fsetmod(FILE *fp,char mod)
{ return _setmode (_fileno(fp),mod=='b'?_O_BINARY:_O_TEXT); }
 
#ifdef __cplusplus
extern "C" {
#endif
 
__declspec(dllexport)
void **
#if defined(__BORLANDC__)
__stdcall /* __stdcall appears to be the only way to get the name
* decoration right with Borland C. Otherwise it works
* purely incidentally, as we pass no parameters. */
#else
__cdecl
#endif
OPENSSL_Applink(void)
{ static int once=1;
static void *OPENSSL_ApplinkTable[APPLINK_MAX+1]={(void *)APPLINK_MAX};
 
if (once)
{ OPENSSL_ApplinkTable[APPLINK_STDIN] = app_stdin;
OPENSSL_ApplinkTable[APPLINK_STDOUT] = app_stdout;
OPENSSL_ApplinkTable[APPLINK_STDERR] = app_stderr;
OPENSSL_ApplinkTable[APPLINK_FPRINTF] = fprintf;
OPENSSL_ApplinkTable[APPLINK_FGETS] = fgets;
OPENSSL_ApplinkTable[APPLINK_FREAD] = fread;
OPENSSL_ApplinkTable[APPLINK_FWRITE] = fwrite;
OPENSSL_ApplinkTable[APPLINK_FSETMOD] = app_fsetmod;
OPENSSL_ApplinkTable[APPLINK_FEOF] = app_feof;
OPENSSL_ApplinkTable[APPLINK_FCLOSE] = fclose;
 
OPENSSL_ApplinkTable[APPLINK_FOPEN] = fopen;
OPENSSL_ApplinkTable[APPLINK_FSEEK] = fseek;
OPENSSL_ApplinkTable[APPLINK_FTELL] = ftell;
OPENSSL_ApplinkTable[APPLINK_FFLUSH] = fflush;
OPENSSL_ApplinkTable[APPLINK_FERROR] = app_ferror;
OPENSSL_ApplinkTable[APPLINK_CLEARERR] = app_clearerr;
OPENSSL_ApplinkTable[APPLINK_FILENO] = app_fileno;
 
OPENSSL_ApplinkTable[APPLINK_OPEN] = _open;
OPENSSL_ApplinkTable[APPLINK_READ] = _read;
OPENSSL_ApplinkTable[APPLINK_WRITE] = _write;
OPENSSL_ApplinkTable[APPLINK_LSEEK] = _lseek;
OPENSSL_ApplinkTable[APPLINK_CLOSE] = _close;
 
once = 0;
}
 
return OPENSSL_ApplinkTable;
}
 
#ifdef __cplusplus
}
#endif
#endif
/trunk/tools/itscertgen/common.mk
0,0 → 1,163
export LANG=en_US
ALL_CONFIGURATIONS := POSIX WIN32
.PHONY: all clean tests docs cleandocs distr DUMMY
 
ifeq ($(ARCH),)
ARCH = $(shell gcc -dumpmachine)
GCC := gcc
else
GCC := $(addprefix $(addsuffix -,$(ARCH)), gcc)
endif
 
ifneq ($(findstring w32,$(ARCH)),)
packages := $(filter-out readline threads, $(packages))
CFG += WIN32
else
CFG += POSIX
endif
 
cflags += -Wall
 
ifeq ($(DEBUG),)
DEBUG=no
endif
 
ifeq ($(DEBUG),yes)
cflags += -g -O0
defines += DEBUG
dsuffix = -d
else
defines += NDEBUG
cflags += -O2
endif
 
ifneq ($(filter readline, $(packages)),)
defines += USE_READLINE
libs += -lreadline
endif
 
ifneq ($(filter dmalloc, $(packages)),)
defines += DMALLOC DMALLOC_FUNC_CHECK
libs += -ldmalloc
dsuffix = -dmalloc
endif
 
ifneq ($(filter thread, $(packages)),)
defines += USE_THREADS
libs += -lpthread
endif
 
ifneq ($(filter profile, $(packages)),)
cflags += -pg
endif
 
ifneq ($(filter openssl, $(packages)),)
ifneq ($(findstring mingw32,$(ARCH)),)
includes += C:/OpenSSL-Win32/include
libs += C:/OpenSSL-Win32/lib/MinGW/libeay32.a C:/OpenSSL-Win32/lib/MinGW/ssleay32.a
else
libs += -lssl -lcrypto
endif
endif
 
ifneq ($(filter cxml, $(packages)),)
predirs += cxml
endif
 
ifneq ($(filter cshared, $(packages)),)
predirs += cshared
endif
 
ifeq ($(testdir), )
testdir := tests
endif
 
includes += $(foreach cfg,$(CFG),$(includes-$(cfg)))
defines += $(foreach cfg,$(CFG),$(defines-$(cfg)))
libs += $(foreach cfg,$(CFG),$(libs-$(cfg)))
sources += $(foreach cfg,$(CFG),$(sources-$(cfg)))
headers += $(foreach cfg,$(CFG),$(headers-$(cfg)))
tests += $(foreach cfg,$(CFG),$(tests-$(cfg)))
distfiles += $(foreach cfg,$(CFG),$(distfiles-$(cfg)))
predirs += $(foreach cfg,$(CFG),$(predirs-$(cfg)))
postdirs += $(foreach cfg,$(CFG),$(postdirs-$(cfg)))
 
tests := $(addprefix $(addsuffix /,$(testdir)),$(tests))
sources := $(addprefix $(addsuffix /,$(srcdir)),$(sources))
headers := $(addprefix $(addsuffix /,$(incdir)),$(headers))
 
cflags += $(addprefix -I, $(includes)) $(addprefix -D, $(defines))
 
ifeq ($(BUILDROOT),)
BUILDROOT = .
endif
 
outdir := $(BUILDROOT)/$(ARCH)$(dsuffix)
objdir := $(outdir)/$(PROJECT)
objects := $(patsubst %.c, $(objdir)/%.o, $(sources))
testbins := $(patsubst %.c, $(outdir)/%, $(tests))
dirs := $(objdir) $(outdir)/tests
 
alibnames := $(patsubst %, $(outdir)/lib%.a, $(alibs))
solibnames := $(patsubst %, $(outdir)/lib%.so, $(solibs))
binnames := $(patsubst %, $(outdir)/%, $(bins))
 
ldflags += $(patsubst %, -L%, $(outdir) $(libdirs))
 
ifneq ($(filter cxml, $(packages)),)
libs += $(outdir)/libcxml.a
endif
 
ifneq ($(filter cshared, $(packages)),)
libs += $(outdir)/libcshared.a
endif
 
 
all: $(dirs) $(predirs) $(alibnames) $(solibnames) $(binnames) $(postdirs)
 
tests: all $(testbins)
 
$(predirs) $(postdirs): DUMMY
$(MAKE) -C [email protected] BUILDROOT=$(BUILDROOT)/.. DEBUG=$(DEBUG)
 
$(alibnames): $(outdir)/lib%.a : $(objects)
ar rcs [email protected] $^
 
$(solibnames): $(outdir)/lib%.so : $(objects)
$(GCC) $(cflags) -shared $(ldflags) -o [email protected] $^ $(csharedlib) $(libs)
 
$(binnames): $(outdir)/% : $(objects)
$(GCC) $(cflags) $(ldflags) -o [email protected] $^ $(csharedlib) $(libs)
 
$(testbins): $(alibnames)
$(testbins): $(outdir)/tests/% : tests/%.c
$(GCC) $(cflags) -o [email protected] $< $(alibnames) $(libs)
 
$(dirs):
mkdir -p [email protected]
 
$(objects): $(objdir)/%.o: %.c
@mkdir -p $(dir [email protected])
$(GCC) $(cflags) -o [email protected] -MMD -MF $(objdir)/$*.d -c $<
 
clean:
rm -rf $(outdir) $(addsuffix /*~, . $(subdirs))
 
distfiles += $(wildcard Makefile $(DOXYFILE))
dist:
-rm -rf $(PROJECT) $(PROJECT)-$(shell date -u '+%Y%m%d').tar.gz
mkdir $(PROJECT)
cp --parents $(sources) $(headers) $(distfiles) $(addprefix tests/, $(tests)) $(PROJECT)
tar -zcvf $(PROJECT)-$(shell date -u '+%Y%m%d').tar.gz $(PROJECT)
rm -rf $(PROJECT)
# tar -zcvf $(PROJECT)-$(shell date -u '+%Y%m%d').tar.gz $(sources) $(headers) $(distfiles) $(addprefix tests/, $(tests))
 
ifneq (,$(DOXYFILE))
docs: $(DOXYFILE)
doxygen $(DOXYFILE)
 
cleandocs:
rm -rf doc/html
endif
 
include $(wildcard $(addsuffix /*.d, $(objdir)))
/trunk/tools/itscertgen/mkgmtime.c
0,0 → 1,282
// Found in DeSmuME
// Alexis modified it a tad bit so it would compile as C (opposed to C++)
 
/* lib/mkgmtime.c
 
Copyright (C) 2010 DeSmuME team
 
This file is part of DeSmuME
 
DeSmuME 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.
 
DeSmuME 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 DeSmuME; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
//Taken from newlib 1.18.0 which is licensed under GPL 2 and modified for desmume
 
/*
* mktime.c
* Original Author: G. Haley
*
* Converts the broken-down time, expressed as local time, in the structure
* pointed to by tim_p into a calendar time value. The original values of the
* tm_wday and tm_yday fields of the structure are ignored, and the original
* values of the other fields have no restrictions. On successful completion
* the fields of the structure are set to represent the specified calendar
* time. Returns the specified calendar time. If the calendar time can not be
* represented, returns the value (time_t) -1.
*
* Modifications: Fixed tm_isdst usage - 27 August 2008 Craig Howland.
*/
 
#include <stdlib.h>
#include <time.h>
#include "mkgmtime.h"
 
#define _SEC_IN_MINUTE 60L
#define _SEC_IN_HOUR 3600L
#define _SEC_IN_DAY 86400L
 
static const int DAYS_IN_MONTH[12] =
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 
#define _DAYS_IN_MONTH(x) ((x == 1) ? days_in_feb : DAYS_IN_MONTH[x])
 
static const int _DAYS_BEFORE_MONTH[12] =
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
 
#define _ISLEAP(y) (((y) % 4) == 0 && (((y) % 100) != 0 || (((y)+1900) % 400) == 0))
#define _DAYS_IN_YEAR(year) (_ISLEAP(year) ? 366 : 365)
 
static void validate_structure(struct tm *tim_p)
{
div_t res;
int days_in_feb = 28;
 
/* calculate time & date to account for out of range values */
if (tim_p->tm_sec < 0 || tim_p->tm_sec > 59)
{
res = div (tim_p->tm_sec, 60);
tim_p->tm_min += res.quot;
if ((tim_p->tm_sec = res.rem) < 0)
{
tim_p->tm_sec += 60;
--tim_p->tm_min;
}
}
 
if (tim_p->tm_min < 0 || tim_p->tm_min > 59)
{
res = div (tim_p->tm_min, 60);
tim_p->tm_hour += res.quot;
if ((tim_p->tm_min = res.rem) < 0)
{
tim_p->tm_min += 60;
--tim_p->tm_hour;
}
}
 
if (tim_p->tm_hour < 0 || tim_p->tm_hour > 23)
{
res = div (tim_p->tm_hour, 24);
tim_p->tm_mday += res.quot;
if ((tim_p->tm_hour = res.rem) < 0)
{
tim_p->tm_hour += 24;
--tim_p->tm_mday;
}
}
 
if (tim_p->tm_mon > 11)
{
res = div (tim_p->tm_mon, 12);
tim_p->tm_year += res.quot;
if ((tim_p->tm_mon = res.rem) < 0)
{
tim_p->tm_mon += 12;
--tim_p->tm_year;
}
}
 
if (_DAYS_IN_YEAR (tim_p->tm_year) == 366)
days_in_feb = 29;
 
if (tim_p->tm_mday <= 0)
{
while (tim_p->tm_mday <= 0)
{
if (--tim_p->tm_mon == -1)
{
tim_p->tm_year--;
tim_p->tm_mon = 11;
days_in_feb =
((_DAYS_IN_YEAR (tim_p->tm_year) == 366) ?
29 : 28);
}
tim_p->tm_mday += _DAYS_IN_MONTH (tim_p->tm_mon);
}
}
else
{
while (tim_p->tm_mday > _DAYS_IN_MONTH (tim_p->tm_mon))
{
tim_p->tm_mday -= _DAYS_IN_MONTH (tim_p->tm_mon);
if (++tim_p->tm_mon == 12)
{
tim_p->tm_year++;
tim_p->tm_mon = 0;
days_in_feb =
((_DAYS_IN_YEAR (tim_p->tm_year) == 366) ?
29 : 28);
}
}
}
}
 
 
static time_t _leap_moments[] = {
1341100800,
1230768000,
1136073600
};
time_t addleapseconds(time_t t)
{
int i;
for (i = 0; i < sizeof(_leap_moments) / sizeof(_leap_moments[0]); i++){
if (t >= _leap_moments[i]) break;
}
return t + i;
}
 
 
time_t mktaitime(struct tm *tim_p)
{
time_t t = mkgmtime(tim_p);
if (t >= 0){
t = addleapseconds(t);
}
return t;
}
 
time_t mkgmtime(struct tm *tim_p)
{
time_t tim = 0;
long days = 0;
int year, isdst, tm_isdst;
 
/* validate structure */
validate_structure (tim_p);
 
/* compute hours, minutes, seconds */
tim += tim_p->tm_sec + (tim_p->tm_min * _SEC_IN_MINUTE) +
(tim_p->tm_hour * _SEC_IN_HOUR);
 
/* compute days in year */
days += tim_p->tm_mday - 1;
days += _DAYS_BEFORE_MONTH[tim_p->tm_mon];
if (tim_p->tm_mon > 1 && _DAYS_IN_YEAR (tim_p->tm_year) == 366)
days++;
 
/* compute day of the year */
tim_p->tm_yday = days;
 
if (tim_p->tm_year > 10000
|| tim_p->tm_year < -10000)
{
return (time_t) -1;
}
 
/* compute days in other years */
if (tim_p->tm_year > 70)
{
for (year = 70; year < tim_p->tm_year; year++)
days += _DAYS_IN_YEAR (year);
}
else if (tim_p->tm_year < 70)
{
for (year = 69; year > tim_p->tm_year; year--)
days -= _DAYS_IN_YEAR (year);
days -= _DAYS_IN_YEAR (year);
}
 
/* compute day of the week */
if ((tim_p->tm_wday = (days + 4) % 7) < 0)
tim_p->tm_wday += 7;
 
/* compute total seconds */
tim += (days * _SEC_IN_DAY);
 
/* Convert user positive into 1 */
tm_isdst = tim_p->tm_isdst > 0 ? 1 : tim_p->tm_isdst;
isdst = tm_isdst;
 
//screw this!
 
// if (_daylight)
// {
// int y = tim_p->tm_year + YEAR_BASE;
// if (y == tz->__tzyear || __tzcalc_limits (y))
//{
// /* calculate start of dst in dst local time and
// start of std in both std local time and dst local time */
// time_t startdst_dst = tz->__tzrule[0].change
// - (time_t) tz->__tzrule[1].offset;
// time_t startstd_dst = tz->__tzrule[1].change
// - (time_t) tz->__tzrule[1].offset;
// time_t startstd_std = tz->__tzrule[1].change
// - (time_t) tz->__tzrule[0].offset;
// /* if the time is in the overlap between dst and std local times */
// if (tim >= startstd_std && tim < startstd_dst)
// ; /* we let user decide or leave as -1 */
// else
// {
// isdst = (tz->__tznorth
// ? (tim >= startdst_dst && tim < startstd_std)
// : (tim >= startdst_dst || tim < startstd_std));
// /* if user committed and was wrong, perform correction, but not
// * if the user has given a negative value (which
// * asks mktime() to determine if DST is in effect or not) */
// if (tm_isdst >= 0 && (isdst ^ tm_isdst) == 1)
// {
// /* we either subtract or add the difference between
// time zone offsets, depending on which way the user got it
// wrong. The diff is typically one hour, or 3600 seconds,
// and should fit in a 16-bit int, even though offset
// is a long to accomodate 12 hours. */
// int diff = (int) (tz->__tzrule[0].offset
// - tz->__tzrule[1].offset);
// if (!isdst)
// diff = -diff;
// tim_p->tm_sec += diff;
// validate_structure (tim_p);
// tim += diff; /* we also need to correct our current time calculation */
// }
// }
//}
// }
 
//screw this also
/* add appropriate offset to put time in gmt format */
//if (isdst == 1)
// tim += (time_t) tz->__tzrule[1].offset;
//else /* otherwise assume std time */
// tim += (time_t) tz->__tzrule[0].offset;
 
//and screw this too
/* reset isdst flag to what we have calculated */
tim_p->tm_isdst = isdst;
 
return tim;
}
 
// vim: ts=2 sw=2 et
/trunk/tools/itscertgen/mkgmtime.h
0,0 → 1,40
/* lib/mkgmtime.h
 
Copyright (C) 2010 DeSmuME team
 
This file is part of DeSmuME
 
DeSmuME 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.
 
DeSmuME 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 DeSmuME; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _MKGMTIME_H_
#define _MKGMTIME_H_
 
#include <time.h>
 
#ifdef __cplusplus
extern "C" {
#endif
 
extern time_t mkgmtime(struct tm *tim_p);
extern time_t mktaitime(struct tm *tim_p);
extern time_t addleapseconds(time_t t);
 
 
#ifdef __cplusplus
}
#endif
 
#endif
//_MKGMTIME_H_
/trunk/tools/itscertgen/test_keygen.c
0,0 → 1,48
#include "ecc_api.h"
#include <stdio.h>
static const char *_hex = "0123456789ABCDEF";
static void bn2buf(char * buf, const unsigned char * p)
{
const unsigned char * e = p+32;
for(;p<e;p++){
unsigned char c = *p;
*(buf++) = _hex[c>>4];
*(buf++) = _hex[c&0x0F];
}
*buf = 0;
}
 
int main(int argc, char** argv)
{
ecc_point_t point;
if(0 == ecc_api_init()){
int i;
for(i=0; i<=4; i++){
if(i==1) continue;
point.type = i;
char s[256];
sprintf(s, "key%d.pem", i);
if(0 == ecc_api_keygen(0, 0, s, &point)){
FILE * f;
sprintf(s, "key%d.pnt", i);
f = fopen(s, "w");
if(f){
bn2buf(s, &point.x[0]);
fprintf(f, "x=%s\n", s);
if(point.type == compressed_lsb_y_0){
fprintf(f, "y=0\n");
}else if(point.type == compressed_lsb_y_1){
fprintf(f, "y=1\n");
}else if(point.type == uncompressed){
bn2buf(s, &point.y[0]);
fprintf(f, "y=%s\n", s);
}
fclose(f);
}
}
}
}
ecc_api_done();
return 1;
}
/trunk/tools/itscertgen
Property changes:
Added: svn:ignore
## -0,0 +1,2 ##
+mingw32-d
+msvc
Index: tt3plugins/EtsiItsAdapter/Preserve/CryptoLib.jar
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tt3plugins/EtsiItsAdapter/Preserve/de.fraunhofer.sit.c2x.pki.etsi_ts103097v1114.jar
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tt3plugins/LibItsCam_asn1/lib/LibItsCam_asn1.jar
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tt3plugins/LibItsCdd_asn1/lib/LibItsCdd_asn1.jar
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: tt3plugins/LibItsDenm_asn1/lib/LibItsDenm_asn1.jar
===================================================================
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Index: ttcn/AtsCAM/ItsCam_TestCases.ttcn
===================================================================
--- ttcn/AtsCAM/ItsCam_TestCases.ttcn (revision 1916)
+++ ttcn/AtsCAM/ItsCam_TestCases.ttcn (revision 1917)
@@ -3845,10 +3845,13 @@
// Test Body
t_genCam_Dcc.timeout;
v_referencePosition := f_computePositionUsingDistance(v_referencePosition, v_changePosValue);
- f_utChangePosition ( valueof ( UtChangePosition: {
+ f_utChangePosition(
+ valueof(UtChangePosition: {
latitude := v_referencePosition.latitude,
longitude := v_referencePosition.longitude,
- elevation := 0 } ) );
+ elevation := 0 // FIXME := v_referencePosition.altitude
+ }
+ ));
t_genCam_Dcc.start;
alt {
[] camPort.receive(mw_camInd ( mw_camMsg_BC_refPos ( v_referencePosition ) )){
Index: ttcn/AtsDENM/ItsDenm_TestCases.ttcn
===================================================================
--- ttcn/AtsDENM/ItsDenm_TestCases.ttcn (revision 1916)
+++ ttcn/AtsDENM/ItsDenm_TestCases.ttcn (revision 1917)
@@ -1326,7 +1326,19 @@
// Preamble
f_prInitialState();
f_utTriggerEvent(m_utTriggerEvent(v_situation, m_denmLocation_zeroDelta, c_duration_10sec));
- f_awaitDenMessage ( mw_denmInd ( mw_denmPdu ( mw_denm ( mw_denmMgmtCon ( mw_anyActionId, -, -, -, c_duration_2sec ) ) ) ) , v_denmInd );
+ f_awaitDenMessage(
+ mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_anyActionId, -, -, -,
+ c_duration_2sec
+ )
+ )
+ )
+ ),
+ v_denmInd
+ );
v_actionId := v_denmInd.msgIn.denm.management.actionID;
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
@@ -1498,11 +1510,35 @@
// Preamble
f_prInitialState();
- v_actionId := f_sendDenMessage ( m_denm ( m_denmMgmtCon ( m_tsActionId, -, -, -, v_referenceTime1 ), v_situation, m_denmLocation_zeroDelta ) );
+ v_actionId := f_sendDenMessage(
+ m_denm(
+ m_denmMgmtCon(
+ m_tsActionId,
+ -,
+ -,
+ -,
+ v_referenceTime1
+ ),
+ v_situation,
+ m_denmLocation_zeroDelta
+ )
+ );
v_referenceTime2 := f_getCurrentTime();
v_situation.eventType.subCauseCode := c_vehicleBreakDownSubCauseCode_engineProblem;
- v_actionId := f_sendDenMessage ( m_denm ( m_denmMgmtCon ( m_tsActionId, -, -, -, v_referenceTime2 ), v_situation, m_denmLocation_zeroDelta ) );
+ v_actionId := f_sendDenMessage(
+ m_denm(
+ m_denmMgmtCon(
+ m_tsActionId,
+ -,
+ -,
+ -,
+ v_referenceTime2
+ ),
+ v_situation,
+ m_denmLocation_zeroDelta
+ )
+ );
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
@@ -1510,8 +1546,23 @@
tc_ac.start;
alt {
- [] denmPort.receive ( mw_denmInd ( mw_denmPdu (
- mw_denm ( m_denmMgmtConTermination ( v_actionId, -, -, -, -, v_referenceTime2, isNegation ))))) -> value v_denmInd {
+ [] denmPort.receive(
+ mw_denmInd(
+ mw_denmPdu(
+ mw_denm (
+ m_denmMgmtConTermination(
+ v_actionId,
+ -,
+ -,
+ -,
+ -,
+ v_referenceTime2,
+ isNegation
+ )
+ )
+ )
+ )
+ ) -> value v_denmInd {
tc_ac.stop;
log("*** " & testcasename() & ": PASS: Successfully received expected DENM. ***");
f_selfOrClientSyncAndVerdict(c_tbDone, e_success);
@@ -1583,7 +1634,18 @@
// Preamble
f_prInitialState();
f_utTriggerEvent(m_utTriggerEvent(v_situation, m_denmLocation_zeroDelta, c_duration_10sec));
- f_awaitDenMessage( mw_denmInd ( mw_denmPdu ( mw_denm ( mw_denmMgmtCon ( mw_anyActionId ) ) ) ), v_denmInd );
+ f_awaitDenMessage(
+ mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_anyActionId
+ )
+ )
+ )
+ ),
+ v_denmInd
+ );
v_actionId := v_denmInd.msgIn.denm.management.actionID;
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
@@ -2055,15 +2117,25 @@
testcase TC_DEN_EVRP_BV_01() runs on ItsDenm system ItsDenmSystem {
// Local constants
- const TransmissionInterval c_repetitionInterval := c_interval_1sec; // INTERVAL_1
- const ValidityDuration c_validityDuration := c_duration_10sec; // DURATION_2
- const ValidityDuration c_repetitionDuration := c_validityDuration; // DURATION_1
+ const TransmissionInterval c_repetitionInterval := c_interval_1sec; // INTERVAL_1
+ const ValidityDuration c_validityDuration := c_duration_10sec; // DURATION_2
+ const ValidityDuration c_repetitionDuration := c_validityDuration; // DURATION_1
const float c_lowerRepetitionInterval := int2float(c_repetitionInterval)*0.95;
const float c_upperRepetitionInterval := int2float(c_repetitionInterval)*1.05;
// Local variables
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
- var template (present) DenmInd v_expectedDenmInd :=
- mw_denmInd ( mw_denmPdu ( mw_denm ( mw_denmMgmtCon ( mw_actionId, -, -, c_validityDuration ) ) ) );
+ var template (present) DenmInd v_expectedDenmInd := mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_actionId,
+ -,
+ -,
+ c_validityDuration
+ )
+ )
+ )
+ );
var ActionID v_actionId;
var DenmInd v_denmInd;
// Local timers
@@ -2160,8 +2232,18 @@
const float c_upperRepetitionInterval := int2float(c_repetitionInterval)*1.05;
// Local variables
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
- var template (present) DenmInd v_expectedDenmInd :=
- mw_denmInd(mw_denmPdu(mw_denm( mw_denmMgmtCon( mw_actionId, -, -, c_validityDuration))));
+ var template (present) DenmInd v_expectedDenmInd := mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_actionId,
+ -,
+ -,
+ c_validityDuration
+ )
+ )
+ )
+ );
var ActionID v_actionId;
var DenmInd v_denmInd;
// Local timers
@@ -2176,7 +2258,15 @@
// Preamble
f_prInitialState();
- f_utTriggerEvent( m_utTriggerEvent( v_situation, m_denmLocation_zeroDelta, c_validityDuration, c_repetitionDuration, c_repetitionInterval ) );
+ f_utTriggerEvent(
+ m_utTriggerEvent(
+ v_situation,
+ m_denmLocation_zeroDelta,
+ c_validityDuration,
+ c_repetitionDuration,
+ c_repetitionInterval
+ )
+ );
f_awaitDenMessage(v_expectedDenmInd, v_denmInd);
v_actionId := v_denmInd.msgIn.denm.management.actionID;
v_expectedDenmInd.msgIn.denm.management.actionID := v_actionId;
@@ -2266,8 +2356,18 @@
const ValidityDuration c_repetitionDuration := c_validityDuration;
// Local variables
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
- var template (present) DenmInd v_expectedDenmInd :=
- mw_denmInd(mw_denmPdu(mw_denm(mw_denmMgmtCon(mw_actionId, -, -, c_validityDuration))));
+ var template (present) DenmInd v_expectedDenmInd := mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_actionId,
+ -,
+ -,
+ c_validityDuration
+ )
+ )
+ )
+ );
var ActionID v_actionId;
var DenmInd v_denmInd;
var integer i;
@@ -2363,7 +2463,18 @@
const ValidityDuration c_repetitionDuration := c_duration_5sec;
// Local variables
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
- var template (present) DenmInd v_expectedDenmInd := mw_denmInd(mw_denmPdu(mw_denm(mw_denmMgmtCon(mw_actionId, -, -, c_validityDuration))));
+ var template (present) DenmInd v_expectedDenmInd := mw_denmInd(
+ mw_denmPdu(
+ mw_denm(
+ mw_denmMgmtCon(
+ mw_actionId,
+ -,
+ -,
+ c_validityDuration
+ )
+ )
+ )
+ );
var ActionID v_actionId;
var DenmInd v_denmInd;
var integer i;
@@ -3181,7 +3292,8 @@
m_denm(
m_denmMgmtCon(
v_actionId,
- -, -, -, v_referenceTime2
+ -, -, -,
+ v_referenceTime2
),
v_situation2,
m_denmLocation_zeroDelta
@@ -3434,7 +3546,17 @@
);
f_sleep(1.0);
- v_actionId := f_sendDenMessage ( m_denm ( m_denmMgmtCon ( v_actionId, -, -, -, v_referenceTime2 ), v_situation2, m_denmLocation_zeroDelta ) );
+ v_actionId := f_sendDenMessage(
+ m_denm(
+ m_denmMgmtCon(
+ v_actionId,
+ -, -, -,
+ v_referenceTime2
+ ),
+ v_situation2,
+ m_denmLocation_zeroDelta
+ )
+ );
f_sleep(PX_TNOAC);
for(i:=0; i < lengthof(vc_utEvents)
@@ -3535,7 +3657,18 @@
f_sleep(1.0);
v_detectionTime2 := valueof(v_denm.management.detectionTime) - 1000;
v_actionId := f_sendDenMessage(
- m_denm ( m_denmMgmtCon ( v_actionId, -, - , -, v_detectionTime2, v_referenceTime1 ), v_situation2, m_denmLocation_zeroDelta ) );
+ m_denm(
+ m_denmMgmtCon(
+ v_actionId,
+ -, - ,-,
+ v_detectionTime2,
+ v_referenceTime1
+ ),
+ v_situation2,
+ m_denmLocation_zeroDelta
+ )
+ );
+
f_sleep(PX_TNOAC);
for(i:=0; i < lengthof(vc_utEvents)
and not match(v_actionId, vc_utEvents[i].denMsg.denm.management.actionID)
@@ -4522,10 +4655,12 @@
mw_denmInd(
mw_denmPdu(
mw_denm(
- mw_denmMgmtCon ( v_actionId, - )
+ mw_denmMgmtCon(
+ v_actionId
)
)
)
+ )
) {
tc_ac.stop;
log("*** " & testcasename() & ": PASS: DENM re-forwarded with correct isNegation ***");
@@ -4535,10 +4670,12 @@
mw_denmInd(
mw_denmPdu(
mw_denm(
- mw_denmMgmtCon ( v_actionId, - )
+ mw_denmMgmtCon(
+ v_actionId
)
)
)
+ )
) {
tc_ac.stop;
log("*** " & testcasename() & ": FAIL: DENM re-forwarded with incorrect isNegation ***");
/trunk/ttcn/AtsSecurity/ItsSecurity_TestCases.ttcn3
82,7 → 82,11
var LongPosVector v_longPosVectorIut;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
v_longPosVectorIut := f_getPosition(c_compIut);
118,7 → 122,7
/**
* @desc Check that IUT sends the message signed with the digest pointing to the AT certificate
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
153,12 → 157,16
*/
testcase TC_SEC_ITSS_SND_MSG_04_01() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var SecuredMessage v_recv;
var Certificate v_cert;
var LongPosVector v_longPosVectorIut;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
216,7 → 224,7
/**
* @desc Check that IUT uses the AT certificate to sign messages
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
246,14 → 254,22
*/
testcase TC_SEC_ITSS_SND_MSG_04_02() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var SecuredMessage v_recv;
var Certificate v_cert;
var LongPosVector v_longPosVectorIut;
// Test component configuration
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
v_longPosVectorIut := f_getPosition(c_compIut);
// Test adapter configuration
// Preamble
f_prNeighbour();
291,7 → 307,7
/**
* @desc Check that the SecuredMessage signature containes the ECC point of type set to either compressed_lsb_y_0, compressed_lsb_y_1 or x_coordinate_only
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
320,12 → 336,20
*/
testcase TC_SEC_ITSS_SND_MSG_05_01() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var LongPosVector v_longPosVectorIut;
// Test component configuration
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
v_longPosVectorIut := f_getPosition(c_compIut);
// Test adapter configuration
// Preamble
f_prNeighbour();
429,7 → 453,7
Check that the header fields are in the ascending order according to the numbering of the enumeration except of the signer_info, which is encoded first.
Check that generation_time_standard_deviation, expiration, encryption_parameters, recipient_info are not used
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
468,7 → 492,12
var HeaderFieldType v_previousHeaderType;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
596,6 → 625,10
var boolean v_nextCamWithCertificate := false;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
648,6 → 681,7
repeat;
}
} else {
t_minTransInterval.stop;
log("*** " & testcasename() & ": FAIL: Certificate in received CAM ***");
f_selfOrClientSyncAndVerdictTestBody(c_tbDone, e_error);
}
692,7 → 726,7
/**
* @desc Check that the secured CAM contains the signer_info field of certificate when over the time of one second no other SecuredMessage contained a signer_info of type certificate..
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
739,6 → 773,10
var boolean v_nextCamWithCertificate := false;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
826,9 → 864,9
/**
* @desc Check that the secured CAM contains the signer_info field of certificate when the timeout of 1 second has been
* expired after the previous CAM containing the certificate.
* expired after the previous CAM containing the certificate.
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
873,6 → 911,10
var boolean v_nextCamWithCertificate := false;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
960,7 → 1002,7
/**
* @desc Check that SUT send certificate to unknown ITS-S
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1016,6 → 1058,10
var GeoNetworkingInd v_geoNwInd;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
1039,7 → 1085,7
log("*** " & testcasename() & ": INFO: Initial conditions: First CAM message with certificate received ***");
// Send secured message from unknown ITS-S
f_sendSecuredCam(cc_taCertB);
f_sendSecuredCam(cc_taCert_B);
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
}
1097,7 → 1143,7
/**
* @desc Check that IUT restart the certificate sending timer when the certificate has been sent
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1140,6 → 1186,10
var GeoNetworkingInd v_geoNwInd;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ": ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
1164,7 → 1214,7
// Send secured message with request for unrecognized certificate
f_sendSecuredCam(
cc_taCertB,
cc_taCert_B,
{
m_header_field_unrecognised_certificate(
f_HashedId3FromHashedId8(
1228,7 → 1278,7
/**
* @desc Check that SUT send certificate when requested
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1280,6 → 1330,10
var GeoNetworkingInd v_geoNwInd;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ": ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
1304,7 → 1358,7
// Send secured message with request for unrecognized certificate
f_sendSecuredCam(
cc_taCertB,
cc_taCert_B,
{
m_header_field_unrecognised_certificate( // containing digests
f_HashedId3FromHashedId8( // containing HashedId3 value
1369,7 → 1423,7
/**
* @desc Check that SUT send certificate_chain when requested
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1423,6 → 1477,10
var GeoNetworkingInd v_geoNwInd;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ": ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
1447,7 → 1505,7
// Send secured message with request for unrecognized certificate
f_sendSecuredCam(
cc_taCertB,
cc_taCert_B,
{
m_header_field_unrecognised_certificate( // containing digests
f_HashedId3FromHashedId8( // containing HashedId3 value
1536,7 → 1594,7
/**
* @desc Check that message generation time is inside the validity period of the signing certificate
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1593,6 → 1651,10
var integer v_currentTime, v_lowerBound, v_upperBound;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ": ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
1677,7 → 1739,7
/**
* @desc Check secured CAM its_aid value
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1701,9 → 1763,19
* @reference ETSI TS 103 097 V1.1.14, clause 7.1
*/
testcase TC_SEC_ITSS_SND_CAM_11_01() runs on ItsGeoNetworking system ItsSecSystem {
// Test component configuration
// Local variables
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
1751,7 → 1823,7
/**
* @desc Check that the IUT sends certificate request when it receives a message from unknown station
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1788,13 → 1860,23
* @reference ETSI TS 103 097 V1.1.14, clause 7.1
*/
testcase TC_SEC_ITSS_SND_CAM_12_01() runs on ItsGeoNetworking system ItsSecSystem {
// Test component configuration
// Local variables
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
// Send secured message from unknown ITS-S
f_sendSecuredCam(cc_taCertB);
f_sendSecuredCam(cc_taCert_B);
geoNetworkingPort.clear;
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
1839,7 → 1921,7
/**
* @desc Check that the Secured CAM contains exactly one non-empty payload of type signed.
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1869,12 → 1951,19
* @reference ETSI TS 103 097 V1.1.14, clause 7.1
*/
testcase TC_SEC_ITSS_SND_CAM_14_01() runs on ItsGeoNetworking system ItsSecSystem {
// Local variables
// Local variables
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
1911,7 → 2000,7
* Check that the signature contained in the SecuredMessage is calculated over the
* right fields by cryptographically verifying the signature.
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
1971,9 → 2060,17
var Certificate v_certificate;
var boolean v_certificateReceived := false;
// Test component configuration
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
4434,7 → 4531,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredCam(cc_taCertA, omit, e_certificate);
v_securedGnPdu := f_sendSecuredCam(cc_taCert_A, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
4532,7 → 4629,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredCam(cc_taCertA, omit, e_certificate_digest_with_sha256);
v_securedGnPdu := f_sendSecuredCam(cc_taCert_A, omit, e_certificate_digest_with_sha256);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
4643,7 → 4740,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredCam(cc_taCertA, omit, e_certificate_chain);
v_securedGnPdu := f_sendSecuredCam(cc_taCert_A, omit, e_certificate_chain);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
4702,7 → 4799,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredCam(cc_taCertA);
v_securedGnPdu := f_prepareSecuredCam(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.protocol_version := 1;
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
4763,7 → 4860,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredCam(cc_taCertA);
v_securedGnPdu := f_prepareSecuredCam(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.protocol_version := 3;
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
4833,7 → 4930,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_digest(
4913,7 → 5010,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_generation_time(1000 * f_getCurrentTime()), // In us
m_header_field_its_aid_CAM
4977,7 → 5074,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_generation_time(1000 * f_getCurrentTime()), // In us
m_header_field_its_aid_CAM,
5054,7 → 5151,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_digest(
5137,7 → 5234,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_digest(
5221,7 → 5318,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_digest(
5309,7 → 5406,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_digest(
5390,7 → 5487,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_its_aid_DENM
}
5873,7 → 5970,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredCam(cc_taCertA);
v_securedGnPdu := f_prepareSecuredCam(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.trailer_fields := {};
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
5937,7 → 6034,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredCam(cc_taCertA);
v_securedGnPdu := f_prepareSecuredCam(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.trailer_fields[1] := v_securedGnPdu.gnPacket.securedMsg.trailer_fields[0];
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
6017,7 → 6114,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
omit,
e_certificate
);
6102,7 → 6199,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
omit,
e_certificate_digest_with_sha256
);
6173,7 → 6270,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertF,
cc_taCert_F,
{
m_header_field_signer_info(
m_signerInfo_certificate(
6250,7 → 6347,7
// Test Body
v_securedGnPdu := f_prepareSecuredCam(
cc_taCertA,
cc_taCert_A,
{
m_header_field_signer_info(
m_signerInfo_certificate(
6362,7 → 6459,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertA, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_A, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
6466,7 → 6563,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertB, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_B, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
6572,7 → 6669,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertC, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_C, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
6678,7 → 6775,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertD, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_D, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
6784,7 → 6881,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertD, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_D, omit, e_certificate);
f_sleep(PX_TAC);
for (i := 0; i < lengthof(vc_utInds) and not match(vc_utInds[i].rawPayload, v_securedGnPdu.gnPacket.packet.payload.rawPayload); i := i + 1) {
6843,7 → 6940,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredDenm(cc_taCertA);
v_securedGnPdu := f_prepareSecuredDenm(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.protocol_version := 1;
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
6904,7 → 7001,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_prepareSecuredDenm(cc_taCertA);
v_securedGnPdu := f_prepareSecuredDenm(cc_taCert_A);
v_securedGnPdu.gnPacket.securedMsg.protocol_version := 1;
f_sendGeoNetMessage(m_geoNwReq_linkLayerBroadcast(v_securedGnPdu));
6969,7 → 7066,7
// Test Body
v_securedGnPdu := f_prepareSecuredDenm(
cc_taCertA,
cc_taCert_A,
{
m_header_field_its_aid_CAM
}
7044,7 → 7141,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertB, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_B, omit, e_certificate);
f_sleep(PX_TNOAC);
if (lengthof(vc_utInds) == 0) {
7111,7 → 7208,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertC, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_C, omit, e_certificate);
f_sleep(PX_TNOAC);
if (lengthof(vc_utInds) == 0) {
7178,7 → 7275,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertD, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_D, omit, e_certificate);
f_sleep(PX_TNOAC);
if (lengthof(vc_utInds) == 0) {
7245,7 → 7342,7
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
// Test Body
v_securedGnPdu := f_sendSecuredDenm(cc_taCertE, omit, e_certificate);
v_securedGnPdu := f_sendSecuredDenm(cc_taCert_E, omit, e_certificate);
f_sleep(PX_TNOAC);
if (lengthof(vc_utInds) == 0) {
7271,7 → 7368,7
/**
* @desc Check that AT certificate has version 2
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
7298,10 → 7395,19
* @reference ETSI TS 103 097 V1.1.14, clause 6.1
*/
testcase TC_SEC_SND_CERT_01_01() runs on ItsGeoNetworking system ItsSecSystem {
// Local variables
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
7347,7 → 7453,7
/**
* @desc Check that AA certificate has version 2
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
7375,15 → 7481,23
* @reference ETSI TS 103 097 V1.1.14, clause 6.1
*/
testcase TC_SEC_SND_CERT_01_02() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var SecuredMessage v_recv;
var Certificate v_cert;
var SignerInfo v_si;
var HashedId8 v_digest;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
7438,7 → 7552,7
/**
* @desc Check that the certificate chain is valid: Check signer_info
* <pre>
* Pics Selection: none
* Pics Selection: PICS_GN_SECURITY
* Config Id: CF01
* Initial conditions:
* with {
7473,9 → 7587,17
var SignerInfo v_si;
var HashedId8 v_digest;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
7548,18 → 7670,28
* }
* }
* }
* @remark Certificate: cc_taCert_C
* </pre>
* @reference ETSI TS 103 097 V1.1.14, clauses 4.2.21, 4.2.24
*/
testcase TC_SEC_SND_CERT_04_01() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var Certificate v_cert;
var ValidityRestriction v_vr;
var integer v_counter;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
vc_hashedId8ToBeUsed := cc_iutCert_C;
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
7658,15 → 7790,22
* @reference ETSI TS 103 097 V1.1.14, clauses 4.2.21, 4.2.24
*/
testcase TC_SEC_SND_CERT_04_02() runs on ItsGeoNetworking system ItsSecSystem {
// Local declarations
// Local variables
var CertificateChain v_chain;
var ValidityRestriction v_vr, v_vri; // current and issuing cert validity restrictions
var boolean f_vr, f_vri;
// Test control
if (not(PICS_GN_SECURITY)) {
log("*** " & testcasename() & ":ERROR: 'PICS_GN_SECURITY' required for executing the TC ***");
stop;
}
// Test component configuration
f_cf01Up();
// Test adapter configuration
// Preamble
f_prNeighbour();
f_selfOrClientSyncAndVerdictPreamble(c_prDone, e_success);
9578,10 → 9717,10
f_selfOrClientSyncAndVerdictTestBody(c_tbDone, e_error);
}
} // End of 'for' statement
if (not match(v_aid_ssp_list[v_counter], (all from v_aid_list))) {
log("*** " & testcasename() & ": FAIL: ITS-AID " & int2str(v_aid_ssp_list[v_counter].its_aid) & " is not exist in AA certificate ***");
f_selfOrClientSyncAndVerdictTestBody(c_tbDone, e_error);
}
// if (not match(v_aid_ssp_list[v_counter], (all from v_aid_list))) {
// log("*** " & testcasename() & ": FAIL: ITS-AID " & int2str(v_aid_ssp_list[v_counter].its_aid) & " is not exist in AA certificate ***");
// f_selfOrClientSyncAndVerdictTestBody(c_tbDone, e_error);
// }
// TODO Not possible due to typing To be removed
// if (lengthof(v_aid_ssp_list[v_counter].service_specific_permissions.sspContainer) > 31) {
// log("*** " & testcasename() & ": FAIL: ITS-AID " & int2str(v_aid_ssp_list[v_counter].its_aid) & " has too long service_specific_permissions ***");
/trunk/unittests/codec/ttcn/test_LibItsCam_TypesAndValues.ttcn
105,15 → 105,14
}
testcase tc_changePosition() runs on TCType system TCType {
test_PDU<UtCamTrigger>(
m_changePosition(
UtChangePosition: {
latitude := 49845,
longitude := 631,
elevation := 512
}
),
false);
test_PDU<UtChangePosition>(
UtChangePosition: {
latitude := 49845,
longitude := 631,
elevation := 512
},
false
);
}
testcase tc_changeSpeed() runs on TCType system TCType {
392,7 → 391,8
// steeringWheelAngle := omit,
// lateralAcceleration := omit,
// verticalAcceleration := omit,
// performanceClass := omit
// performanceClass := omit,
// cenDsrcTollingZone := omit
// }
// },
// lowFrequencyContainer := {
473,7 → 473,7
)
),
true,
oct2bit('01020001B20788B80059F48D95CDEFC8C5E0020020002461A83C000004805A100C4528399D4C387FFF80'O)
oct2bit('01020001B20788B80059F48D95CDEFC8C6000200200030D41E0000012016840310A50733A9870FFFD0'O)
);
}
/trunk/unittests/codec/ttcn/test_LibItsDenm_TypesAndValues.ttcn
55,9 → 55,7
m_denmLocation_zeroDelta
)
)
),
true,
oct2bit('01010001B207C0000D903800000000006072000000188593E91B2B9BDF918C000400400061A80000B6000037FFFDFFFF63390100'O)
)
);
}
/trunk/unittests/codec/ttcn/test_LibItsGeoNetworking_TypesAndValues.ttcn
134,7 → 134,7
geoAreaPosLatitude := 298376,
geoAreaPosLongitude := 32745,
distanceA := 1234,
distanceB := 5678,
distanceB := 6078,
angle := 9123
}
1221,7 → 1221,7
testcase tc_GeoNetReq_NwShbPacketWithBtpPayloadDenm() runs on TCType system TCType {
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
var GeoNetworkingReq v_gnReq;
var octetstring v_buffer := '01002B0A2050800000380A00BC21A4FEDECABEEF0001E240000012F8000002A380372694000000000000000001010001B207C0000D903800000000006072000000188593E91B2B9BDF918C000400400061A80000B6000037FFFDFFFF63390100FFFFFFFFFFFF'O;
var octetstring v_buffer := '01002B0A20508000003C0A00BC21A4FEDECABEEF0001E240000012F8000002A3803726940000000007D2000001010001B207C70000D90380000A0843ABBBE28210EAF534FA46CAE6F7E4630001001000186A000009600C05B00000DFFFF7FFFD8CE40400FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_btpB) {
log("PX_GN_UPPER_LAYER shall be set to e_btpB");
1256,7 → 1256,7
v_gnReq,
false
);
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 56;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 60;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_buffer
1418,7 → 1418,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 46;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 45;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
1829,7 → 1829,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 46;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 45;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
1924,7 → 1924,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 46;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 45;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
2031,7 → 2031,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 56;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 60;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
2194,7 → 2194,7
*/
testcase tc_GeoNetReq_AnycastPacket() runs on TCType system TCType {
var GeoNetworkingReq v_gnReq;
var octetstring v_buffer := '01002B0A00308000000F0A001DE60000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D2162E23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
var octetstring v_buffer := '01002B0A00308000000F0A001DE60000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D217BE23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_any) {
log("PX_GN_UPPER_LAYER shall be set to e_any");
2309,7 → 2309,7
testcase tc_GeoNetReq_AnycastPacketWithHopLimit() runs on TCType system TCType {
var GeoNetworkingReq v_gnReq;
var ExtendedHeader v_header := null;
var octetstring v_buffer := '01002B0A00308000000F05001DE60000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D2162E23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
var octetstring v_buffer := '01002B0A00308000000F05001DE60000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D217BE23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_any) {
log("PX_GN_UPPER_LAYER shall be set to e_any");
2661,7 → 2661,7
testcase tc_GeoNetReq_BroadcastPacket() runs on TCType system TCType {
var GeoNetworkingReq v_gnReq;
var ExtendedHeader v_header := null;
var octetstring v_buffer := '01002B0A00418000000F0A000D800000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D2162E23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
var octetstring v_buffer := '01002B0A00418000000F0A000D800000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D217BE23A3000044454641554C545F5041594C4F4144FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_any) {
log("PX_GN_UPPER_LAYER shall be set to e_any");
2821,7 → 2821,7
var GnNonSecuredPacket v_gnNonSecuredPacket;
var GeoNetworkingPacket v_geoNetworkingPacket;
var template (value) SituationContainer v_situation := m_situation(c_causeVehicleBreakdown, c_subCauseCode_Unavailable);
var octetstring v_buffer := '01002B0A2041800000380A000D800000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D2162E23A300000000000001010001B207C0000D903800000000006072000000188593E91B2B9BDF918C000400400061A80000B6000037FFFDFFFF63390100FFFFFFFFFFFF'O;
var octetstring v_buffer := '01002B0A20418000003C0A000D800000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D217BE23A3000007D2000001010001B207C70000D90380000A0843F2F2828210FCBCACFA46CAE6F7E4630001001000186A000009600C05B00000DFFFF7FFFD8CE40400FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_btpB) {
log("PX_GN_UPPER_LAYER shall be set to e_btpB");
2857,7 → 2857,7
v_gnReq,
false,
oct2bit(v_buffer));
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 56;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 60;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_buffer
3049,7 → 3049,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 56;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 60;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
3157,7 → 3157,7
}
setverdict(pass, "Encoding passed.");
// Decode it
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 56;
v_gnReq.msgOut.gnPacket.packet.commonHeader.plLength := 60;
test_decodePDU<GeoNetworkingReq>(
v_gnReq,
v_encMsg
3205,7 → 3205,7
*/
testcase tc_GeoNetInd_SecuredBeacon() runs on TCType system TCType {
var GeoNetworkingInd v_gnInd;
var octetstring v_decMsg := '02002B0A021E8001963A7C716A20569D00000134D2197F537003000004D20000162E002F01200010800000000100BC21A4FEDECABEEF0001E240000012F8000002A38037269443010002E0EF081A49ABA0570F5EDCAACD65C8509EBFD4132CEB8E80904E1EAC489C12D17672C967428FFF851304CC83D914EE73AD12892F2BC55B092CBFF59147643DBBFFFFFFFFFFFF'O;
var octetstring v_decMsg := '02002B0A021E80015024A224729A4C800000013981FD42941003000004D20000162E002F01200010800000000100BC21A4FEDECABEEF0001E240000012F8000002A380372694430100027714B9A92AC942E36C0B8A87C516770251A24AB00394FBD2C01A9105CA677A95968A816454027D23D26F0CD335C12D111D8FD7D02A85DA45FB2F3E6C99BFE0EAFFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_any) {
log("PX_GN_UPPER_LAYER shall be set to e_any");
3236,7 → 3236,7
// Check signature
if (decvalue(oct2bit(v_decMsg), v_gnInd) == 0) {
if (f_verifyGnSecuredMessageSignatureWithCertificate(v_gnInd.msgIn.gnPacket.securedMsg,vc_atCertificate) == true) {
if (f_verifyGnSecuredMessageSignatureWithCertificate(v_gnInd.msgIn.gnPacket.securedMsg, vc_atCertificate) == true) {
setverdict(pass, "Signature check succeed.");
} else {
setverdict(fail, "Signature check failed.");
3277,7 → 3277,7
*/
testcase tc_GeoNetInd_SecuredLsRequestPacket() runs on TCType system TCType {
var GeoNetworkingInd v_gnInd;
var octetstring v_decMsg := '02002B0A021E8001963A7C716A20569D00000134D261A4425003000004D20000162E002F012C0060800000000A0030390000BC21A4FEDECABEEF0001E240000012F8000002A380372694BC21A4FEDECABEEF43010002B48FF2B34AEDAFC616F54EB204C556E5E7877A8F4A3AD14B38E06272D593FFF8C2C1E6A0F5F22A72AE235E8898920D9B4ADAE83178F30E282F796823EE139CA0FFFFFFFFFFFF'O;
var octetstring v_decMsg := '02002B0A021E80015024A224729A4C800000013981FF5C67A803000004D20000162E002F012C0060800000000A0030390000BC21A4FEDECABEEF0001E240000012F8000002A380372694BC21A4FEDECABEEF430100027C8D3FE7CCA30FFBE6CC7D3C7C31F06EDB8976268F584052C4112C9D9FA1180DF3F389DB64926D40C9A4EB72BCB81A41641018A980703C3CB1BD1BF7482B58E6FFFFFFFFFFFF'O;
if (PX_GN_UPPER_LAYER != e_any) {
log("PX_GN_UPPER_LAYER shall be set to e_any");
3396,7 → 3396,7
mw_geoNwAnyPacket_withPayload(
?
))),
'02002b0a020181198002020901b893358ab25faf64010080950000045fe633945b4c1a08d904dfb35fb19ef2967e2c739725d5c0e868d8682743f9390369985c3af3aa54e489c4a7d0381cfd9dfb6d71bb6e6059061f16dafd05da46010100042c560cb703294825e40d5d850ab4fef24e5b0dee3e12a4ce0747c4f31db1b147a1cbc5690f3929a5e7263e92c07db2e606d4da72ebe2732e4bd61c58aae807630220210ac040800100c04081010024015411aa6d5a391aed0303181db9cf7c052616001db9566e0526872a1d53f0d0052783500000570941dabbc94fd3607250d96fd1bef305f92113b8eef39772232c0fcdb951e4dcc6d99b8c8ca94a0ac14a7a46707b83a80820adca58b6f1e3fea7fe6e0752ba0220210ac040800100c0408101002401540086ed5a391aed0303181db9cf7c052616001db9566e0526872a1d53f0d00527835000009ba18503dfc211994cfd1a1ecf71f306da9e6980ac2fb091d0797d9b155a20864930abcb59b4feda7a59c3c78cdafce8e804f6fe8cab94afcc84bf568d46497d0000000148c5afcc2d05000254005210508000002e0a00bc21a4fedecabeeff6f50875000012f8000002a380372694000000000000000001020001b20788b80059f48d95cdefc8c5e0020020002461a83c000004805a100c4528399d4c387fff804301000200005cb251c659b90920b87fa55ca4e831a986b77c0f145a45b8e49674ee0dcf68b505c5c5bd546da38f379edc6bc8b96acf4736e47412065005665af7aed2a39012'O
'02002B0A028124800202015024A224729A4C80010080950000044D8F459AD7485EF21803B7CB9B6D857CCD721542BFE99FACFFB3DF44C34140593126362569F78A5169EBB0FC878B9AD07DDC2B36D01E83C02EABE71210C879DF010100046AE865F5E00290B2BE93D1F26D9857F7B19E53D213846B2C276247DCCED022AC244258C9D1ACF2E3F8BF750F952B02C81ACA013AC018C56F85C4A7E68E9587780220210AC040800100C0408101002401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D00527835000002E7F2FCB38E1418219A51808983988739DFDC649DA209EA6C59319117374E0ED4DBED15F51C6D3106883DCE308A9E6A8E314EA24E8322DDFB02971FDB8C22B26000001398255A96C2803000004D20000162E002F05C04081017020418000003C0A000D800000A832A40102030405000011E90000007E0000007B002D007D00048D8800007FE904D217BE23A3000007D2000001010001B207C70000D90380000A084446EB02821111BACCFA46CAE6F7E4630001001000186A000009600C05B00000DFFFF7FFFD8CE40400430100024AD9813B0BE1B67A8C1AB211D28C6BFC5FE3EA1A3AC5349DB6FF06FBAFF708C54466E608FEAE8AA565F4EA793CCC5D1726679CD59FFA6FD00FB5A61569D343E4FFFFFFFFFFFF'O
);
}
3425,10 → 3425,52
mw_geoNwAnyPacket_withPayload(
?
))),
'02002B0A020181198002020901B893358AB25FAF64010080950000045FE633945B4C1A08D904DFB35FB19EF2967E2C739725D5C0E868D8682743F9390369985C3AF3AA54E489C4A7D0381CFD9DFB6D71BB6E6059061F16DAFD05DA46010100042C560CB703294825E40D5D850AB4FEF24E5B0DEE3E12A4CE0747C4F31DB1B147A1CBC5690F3929A5E7263E92C07DB2E606D4DA72EBE2732E4BD61C58AAE807630220210AC040800100C04081010024015411AA6D5A391AED0303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000570941DABBC94FD3607250D96FD1BEF305F92113B8EEF39772232C0FCDB951E4DCC6D99B8C8CA94A0AC14A7A46707B83A80820ADCA58B6F1E3FEA7FE6E0752BA000001358CEAA7398005000254005210508000002E0A00BC21A4FEDECABEEF535AEF38000012F8000002A3803726940000000007D1000001020001B20788B80059F48D95CDEFC8C5E0020020002461A83C000004805A100C4528399D4C387FFF804301000247C9F3161E20F8B61857117967DA83EA4A1667A27B0462F2B07197C3F82FC816F336F1C803BD1B3E62B1B7D3141921485049DEA8ECD22E7F2D27077E98AA74EC010002B4A06C592A8B49CBBCC35D864A427C7A020CB2E535B043DD06828ED9310859A9B90847545A7845CAF565D430C8187A784E9DB4495A16D694E5FAA67C30785550'O
'02002B0A028119800202015024A224729A4C80010080950000044D8F459AD7485EF21803B7CB9B6D857CCD721542BFE99FACFFB3DF44C34140593126362569F78A5169EBB0FC878B9AD07DDC2B36D01E83C02EABE71210C879DF010100046AE865F5E00290B2BE93D1F26D9857F7B19E53D213846B2C276247DCCED022AC244258C9D1ACF2E3F8BF750F952B02C81ACA013AC018C56F85C4A7E68E9587780220210AC040800100C0408101002401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D00527835000002E7F2FCB38E1418219A51808983988739DFDC649DA209EA6C59319117374E0ED4DBED15F51C6D3106883DCE308A9E6A8E314EA24E8322DDFB02971FDB8C22B260000013981EF9678B805C04080015110508000002D0A00BC21A4FEDECABEEF0001E240000012F8000002A3803726940000000007D2000001020001B20788B80059F48D95CDEFC8C6000200200030D41E0000012016840310A50733A9870FFFD0430100022457F8BB0467B2C62318395A56BBF0004BE8E486D1186586CB385D332DDE83EA511F53431CE38F6F13835DEA3AF3F20D3FC84341EE87090992FC1E05AD6ECA2BFFFFFFFFFFFF'O
);
}
/**
* @desc validate secured GeoNetworkingInd/SHB with certificates chain
* @verdict Pass on success, Fail otherwise
*/
testcase tc_GeoNetInd_SecuredShbCAMWithCertificatesChain() runs on TCType system TCType {
var GeoNetworkingInd v_gnInd;
var octetstring v_decMsg := '02002B0A028231800382200201FABD6A8FA6CAB3740210455453495F506C7567746573745F41418091000004F4A81DE17B3BBFD8ABB276D9F1FF8290FCC5FF8863E8B251398E9DDB81A9FDC1268AED92B4B15099AB0BCE24378BE907D5EF0E7F3FB69C1A84C9FC5452A20A2C010100043288A11BE5A5781D7C206DAF3080FBEB52AE945F809CF266D029EA1CD57042303288A11BE5A5781D7C206DAF3080FBEB52AE945F809CF266D029EA1CD570423002202006C04080C040812401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D00527835000009C26B3AA8A670471D89ECD7DB76E907B5D7F5C519E6C2FCB362A7DC225172BD176E7AF6E54754D30B4F18F80B9130B80C99EAAAF65C2A9D8A587C9B7ED629F6202015024A224729A4C80010080950000044D8F459AD7485EF21803B7CB9B6D857CCD721542BFE99FACFFB3DF44C34140593126362569F78A5169EBB0FC878B9AD07DDC2B36D01E83C02EABE71210C879DF010100046AE865F5E00290B2BE93D1F26D9857F7B19E53D213846B2C276247DCCED022AC244258C9D1ACF2E3F8BF750F952B02C81ACA013AC018C56F85C4A7E68E9587780220210AC040800100C0408101002401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D00527835000002E7F2FCB38E1418219A51808983988739DFDC649DA209EA6C59319117374E0ED4DBED15F51C6D3106883DCE308A9E6A8E314EA24E8322DDFB02971FDB8C22B260000013981F04477B005C04080015110508000002D0A00BC21A4FEDECABEEF0001E240000012F8000002A3803726940000000007D2000001020001B20788B80059F48D95CDEFC8C6000200200030D41E0000012016840310A50733A9870FFFD043010002388DEF19AE517360CA2D84BF2CE360B6B65B553A2D21B8329DC9897DFD45117452EAD22250846919E58E0C7E28A25F69423A120491D17BEB08FD38C3A454E63CFFFFFFFFFFFF'O;
var bitstring v_decode;
if ((PX_GN_UPPER_LAYER != e_btpA) and (PX_GN_UPPER_LAYER != e_btpB)) {
log("PX_GN_UPPER_LAYER shall be set to e_btpA or e_btpB");
setverdict(inconc);
stop;
}
// Load certificates & keys
if (f_loadCertificates("cfg01") == false) {
setverdict(fail);
stop;
}
f_setGenerationLocation(
f_getTsLatitude(),
f_getTsLongitude()
);
test_decodePDU<GeoNetworkingInd>(
mw_geoNwInd(
mw_geoNwSecPdu(
mdw_securedMessage(
superset(
mw_header_field_signer_info_certificate_chain(
?
)
)
)
)
),
v_decMsg
);
}
} // End of testGeoNetPrimitiveMessages
group testUtEvent {
3437,6 → 3479,20
test_PDU<UtInitialize>(m_gnInitialize, false);
}
testcase tc_UtSecGnInitialize() runs on TCType system TCType {
// Load certificates & keys
if (f_loadCertificates("cfg01") == false) {
setverdict(fail);
stop;
}
f_setGenerationLocation(
f_getTsLatitude(),
f_getTsLongitude()
);
test_PDU<UtInitialize>(m_secGnInitialize(f_calculateDigestFromCertificate(vc_atCertificate)), false);
}
testcase tc_UtInitializeResult() runs on TCType system TCType {
test_decodePDU<UtInitializeResult>(UtInitializeResult:true, '0101'O);
}
/trunk/unittests/codec/ttcn/test_LibItsSecurity_TypesAndValues.ttcn3
11,7 → 11,7
import from LibItsSecurity_Pixits all;
// TestUnits
import from test_CommonCodec all;
import from test_CommonCodec all;
group LibItsSecurity_testCases {
38,8 → 38,7
m_enableSecurity(
"TA_CERT_A"
),
true,
oct2bit('54415F434552545F41'O)
false
);
}
847,6 → 846,44
);
} // End of testcase tc_SubjectAttribute_08
testcase tc_SubjectAttribute_09() runs on TCType system TCType {
test_PDU<SubjectAttribute>(
m_subject_attribute_its_aid_list(
{
1631,
1632
}
),
true,
oct2bit('2004865F8660'O)
);
} // End of testcase tc_SubjectAttribute_09
testcase tc_SubjectAttribute_10() runs on TCType system TCType {
test_PDU<SubjectAttribute>(
m_subject_attribute_its_aid_ssp_list(
{
{
1631,
{
'00'O,
omit
}
},
{
1632,
{
'00'O,
omit
}
}
}
),
true,
oct2bit('2108865F010086600100'O)
);
} // End of testcase tc_SubjectAttribute_10
testcase tc_SubjectAssurance_01() runs on TCType system TCType {
test_PDU<SubjectAssurance>(
m_subjectAssurance(
894,6 → 931,21
);
} // End of testcase tc_ValidityRestriction_04
testcase tc_ValidityRestriction_05() runs on TCType system TCType {
test_PDU<ValidityRestriction>(
m_validity_restriction_region(
m_geographicRegion_circle(
{
43616908,
7052847
},
10000
)
)
);
} // End of testcase tc_ValidityRestriction_05
/**
* @desc Root certificate self signed
* @verdict
1052,6 → 1104,7
var integer v_res;
var HashedId8 v_hashedId8;
var HashedId3 v_hashedId3;
var boolean isSignatureOk;
// AT certificate
v_res := decvalue(oct2bit(c_atCertificate), v_at);
1086,6 → 1139,11
} else {
setverdict(pass, "HashedId3 digest match.");
}
isSignatureOk := f_verifyCertificateSignatureWithIssuingCertificate(
v_at,
v_aa
);
log("Signature AA/AT: ", isSignatureOk);
// AA-CA certificate
v_hashedId8 := f_calculateDigestFromCertificate(v_ca);
1120,10 → 1178,15
setverdict(pass, "All Digests match.");
} // End of testcase tc_Certificate_06
/**
* Test certificate from Denis tool
* @desc
* @verdict
*/
testcase tc_Certificate_07() runs on TCType system TCType {
const octetstring c_rootCertificate := '02000412455453495F506C7567746573745F526F6F748091000004B0280BAABCD2C785974EB25239B6933AA1AF70C2D75190B7B7B53D1E573788F4B41F81BCFF61C8C73D0FCCD602A894C63BF21221E83F015FF1BBD86C92FFE384010100040DC17DEF569DB90C3E4E26B103343E341B328FCFC62B7D169FE9DDD8B7C11448E228BA6A15BB433C03DCAD1F26CAF0FD5773CE25B6C02B82D4AB83CAF70547B902202006C04080C040812401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D00527835000005D052E72F7B299EEB17D20EA1017B490EBA59641ADCE278D8D096D2FA2F91D87A215199038D7717A3F398669ACEAB375B0374585A06D72E4161AD5BB3ADEE400'O;
const octetstring c_aaCertificate := '0201071464374303551A0210455453495F506C7567746573745F41418091000004445C581921F79D72A55107984375641C446DFD2A74EB524DB4E00D6C3ADCE038217319C66433EE802632B2EA3B40552541711A092DE2CA59CB7AA8FD8E8EB819010100043B29698A6F21AD6BF17E5E397B85D404846BA7E5B813BF0CFE761649127B40653B29698A6F21AD6BF17E5E397B85D404846BA7E5B813BF0CFE761649127B406502202006C04080C040812401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000CC73A819EE49906B5A27F9EECF94BA74599A834A6A8DCBE0D6F2D1EC3BB79B622596F07B5D0C777CB4478E8D3F34854F69859EF5D0F0C976800BD57571B13A71'O;
const octetstring c_atCertificate := '020130734784EEE700B70100809500000478A4897E6AC66EF68AE98839F05038D926661D0130EDD65B1EA733824FA4E606B223240C3CF3697EF2C1EC2F3E5D35875D120C5A27E4DDB7C87E01C236A7CF5201010004CF9EDB415860E74350607D809CD1D1EF0CD072E08DED4537F8E27D9583331910EC79523076F5B530926F0CD35EF48E668BCE3A8FB23930BFCFE438745799D8CD0220210AC040800100C0408101002401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000DD8EE9C52CD6AA87C565781D9C299C7057C6322E0815C4428411CDCE2374293EE9E24B5462CA603DC69278A47707191D1F9A6F0EB166C88569F70451C55EEED4'O;
const octetstring c_rootCertificate := '020004004B000004966296BF6D47B5ED66DB32605D1074BCBAC97B5A73FE0D4413F6A1818D6D7E9A966296BF6D47B5ED66DB32605D1074BCBAC97B5A73FE0D4413F6A1818D6D7E9A02E02004865F866009014A9618814C774C0100004337D4953FCEBC99FD481A103514CE23B0E85511D2FC55B8CF98941A5436843ACA9B85949F2DF85F9D4D3E8A150EAB3D5004DF0B3DE3972216328615E5A7F816'O;
const octetstring c_aaCertificate := '0201e76042b201a5435502004b000004b80fbbf4b87fdc12ebd7f3dcb689ec1bd2f2ab4c76c158ae7cf5cefbd5a65bb8b80fbbf4b87fdc12ebd7f3dcb689ec1bd2f2ab4c76c158ae7cf5cefbd5a65bb802e02004865f866015014a9618814c774c01030119ff697804342dd62710000016852db5022a8799bfe0bd9b0226c87a83e3df70557e27b759119550d5273674b42a7e5586af5d61098dabc7785ac3b4189bad28a9fa7f430824fcd0f464b548'O;
const octetstring c_atCertificate := '02012a83ff49822ac92d01004b000004b7e7eab1eb9046831e9b0e868aefb6475b0a6ee8bcd7eadbcb80883f53ae1c51b7e7eab1eb9046831e9b0e868aefb6475b0a6ee8bcd7eadbcb80883f53ae1c5102802104865f010015014a9618814c774c01030119ff697804342dd627100000bcb445ceccdea6b38f196aaab2050d300b966a884a4ac653984b4a3104fbb97cab0d808608cafbb22753d90b0cce256f46830075b6653e973fd56daf99bc4535'O;
var Certificate v_ca;
var Certificate v_aa;
1186,13 → 1249,13
// CA-CA certificate
v_hashedId8 := f_calculateDigestFromCertificate(v_ca);
if (v_hashedId8 != '071464374303551a'O) {
if (v_hashedId8 != 'e76042b201a54355'O) {
setverdict(fail, "Digest does not match.");
stop;
} else {
setverdict(pass, "Digest match.");
}
if (substr(v_hashedId8, lengthof(v_hashedId8) - 3, 3) != f_HashedId3FromHashedId8('071464374303551a'O)) {
if (substr(v_hashedId8, lengthof(v_hashedId8) - 3, 3) != f_HashedId3FromHashedId8('e76042b201a54355'O)) {
setverdict(fail, "HashedId3 digest does not match.");
stop;
} else {
1203,7 → 1266,7
} // End of testcase tc_Certificate_07
testcase tc_Certificate_V2X_Pilot_PKI_08() runs on TCType system TCType {
const octetstring c_rootCertificate := '010100040d50696c6f74504b495f526f6f74808900000410c1b6c130e84711b558e69ce0fbc17de6b9a6c42bb7e1b962ef4cd5b07dadf8d214c65d8b7bd24acce01edfe5f186a94217de25e454763f5d83a1161860d6fc010100049b7d10065669dfe403ceb43e2a57b8061c86b9b8a0adf2ece2fefd5a09872525b89f1d8732a4d761e68446c23fb845cd5c8172d3067b9c61cdefbd6923c1fbc002e00b0105a4ec0110ec21010300000008610502f11fc54ca9d198de0177dd571f12e5945a771e20ceda080a00fbfc0d00b0b38f6ac60c18f2cd79d90c2afe45bd76349e0454817e184f92bf87d7c9b4'O;
const octetstring c_rootCertificate := '01090183CA2168B784FC6C021050696C6F74504B495F5043415F5349548089000004732CA0163B0E3CD6DE8789FED98DE772F3D54EBFF1D44ED556B683B0D8AE837C8B1EB52F25377244298655CDCB3D3CCEA8CEDA1AA5E57920C97FEC38F2237B0B0101000412FD16EA68D73575651CD7AED08023CFDC38AEE3CCAA178D672AB30A6FE7803CAEFCF1F79A373C7D77D84AE2DD079229D50E5745CD73398FB69D902617A6AAB602E00B0105A4EC0110EC210103000000A9A8140518E0C66DED7568E103C9D3927CF83B6D4692B7FA013BE586FB6BA7A17F0DD28FE14317E2B9F141084166F24F0CBD06AB926197F5F6A39C6003640E6400'O;
const octetstring c_rootCertId := '83CA2168B784FC6C'O;
const octetstring c_rootCrlCertificate := '010102b98efc434cffbe83ca2168b784fc6c000000010000002308e8352a08e8352a08faaa2a0000000058ed8b300faccc408d68408da414c251f1f922927c3bfa1d35d4cdbec5e2294e7145eb6b673153c7f2311e3ab79183850aee7395b773c628dfbd5fab283695db'O;
1250,34 → 1313,16
group profileCertificates {
/**
* @desc Validate 'verify signature' external function
* @desc Verify AT certificate signature
*/
testcase tc_profileCertificates_01() runs on TCType system TCType {
var boolean v_result;
v_result := f_verifyWithEcdsaNistp256WithSha256(
'020130734784EEE700B70100809500000478A4897E6AC66EF68AE98839F05038D926661D0130EDD65B1EA733824FA4E606B223240C3CF3697EF2C1EC2F3E5D35875D120C5A27E4DDB7C87E01C236A7CF5201010004CF9EDB415860E74350607D809CD1D1EF0CD072E08DED4537F8E27D9583331910EC79523076F5B530926F0CD35EF48E668BCE3A8FB23930BFCFE438745799D8CD0220210AC040800100C0408101002401146B4B831A5617030303181DB9CF7C052616001DB9566E0526872A1D53F0D0052783500000DD8EE9C52CD6AA87C565781D9C299C7057C6322E0815C4428411CDCE2374293EE9E24B5462CA603DC69278A47707191D1F9A6F0EB166C88569F70451C55EEED4'O,
'0000DD8EE9C52CD6AA87C565781D9C299C7057C6322E0815C4428411CDCE2374293EE9E24B5462CA603DC69278A47707191D1F9A6F0EB166C88569F70451C55EEED4'O,
'78A4897E6AC66EF68AE98839F05038D926661D0130EDD65B1EA733824FA4E606'O,
'B223240C3CF3697EF2C1EC2F3E5D35875D120C5A27E4DDB7C87E01C236A7CF52'O
);
f_loadCertificates("cfg01");
if (v_result == true) {
setverdict(pass, "Certificate verification match");
} else {
setverdict(fail, "Certificate verification mismatch");
}
log (vc_aaCertificate);
log (vc_atCertificate);
} // End of testcase tc_profileCertificates_01
/**
* @desc Verify AT certificate signature
*/
testcase tc_profileCertificates_02() runs on TCType system TCType {
var boolean v_result;
f_loadCertificates("cfg01");
v_result := f_verifyCertificateSignatureWithIssuingCertificate(
vc_atCertificate,
vc_aaCertificate
1289,7 → 1334,7
setverdict(fail, "Certificate verification mismatch");
}
} // End of testcase tc_profileCertificates_02
} // End of testcase tc_profileCertificates_01
} // End of group profileCertificates