Compare Revisions

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

Ignore whitespace Rev 1908 → Rev 1909

/branches/Security/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
/branches/Security/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
/branches/Security/tools/itscertgen/certgen.c
0,0 → 1,1114
#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>
 
// #define DEBUG_BOOKMARKS
 
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;
bookmark_t * bookmarks;
 
unsigned int nTmpValue;
void * key;
}cert_cxml_handler_t;
 
static void bookmark_position(cert_cxml_handler_t * const h, const cxml_tag_t * tag)
{
bookmark_t * s = (bookmark_t*)malloc(sizeof(bookmark_t));
s->prev = h->bookmarks;
h->bookmarks = s;
s->ptr = h->ptr;
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)
{
bookmark_t * s = h->bookmarks;
int size = -1;
if (NULL == s){
assert(s);
}else{
int bcount;
size = h->ptr - s->ptr;
#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*)s->ptr = size;
size = 0;
}else{
memmove(s->ptr + bcount, s->ptr+1, h->ptr - s->ptr - 1);
h->ptr += bcount - 1;
size = cintx_write(size, &s->ptr, s->ptr+bcount, NULL);
}
h->bookmarks = s->prev;
free(s);
}
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);
 
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);
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);
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);
 
 
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){
int 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 unsigned int _createChain = 0;
static unsigned int _outFormat = 0; // binary by default
static const char * _outExtensions[] = {
"bin", "hex", "pem"
};
static const char * _verificationKey = NULL;
static const char * _decriptionKey = NULL;
 
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){
printf("OutFormat=%s\n", _outExtensions[_outFormat]);
return 0;
}
return -1;
}
 
static copt_t options [] = {
{ "h?", "help", COPT_HELP, NULL, "Print this help page" },
{ "i", "in", COPT_STR, &_searchPath, "Certificates search path [Output path by default]" },
{ "o", "out", COPT_STR, &_outPath, "Output path [current dir by default]" },
{ "b", "bin", COPT_BOOL | COPT_CALLBACK, &_out_option, "Binary output format [default]" },
{ "p", "pem", COPT_BOOL | COPT_CALLBACK, &_out_option, "PEM output format" },
{ "x", "hex", COPT_BOOL | COPT_CALLBACK, &_out_option, "Hexadecimal output format" },
{ "n", "name", COPT_STR, &_certName, "Certificate name (take from profile by default)" },
{ "v", "vkey", COPT_STR, &_verificationKey, "Verification public key (generate key pair by default)" },
{ "e", "ekey", COPT_STR, &_decriptionKey, "Decription public key (generate key pair if neccessary)" },
{ "s", "signer", COPT_STR, &_signerName, "Signer certificate name [take from profile by default]" },
{ "r", "reftime", COPT_STR | COPT_CALLBACK, &_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(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);
 
if (_createChain){
 
}
 
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;
int plen = strlen(_outPath) + strlen(_certName);
char * path = malloc(plen + 16);
char * end = cvstrncpy(path, plen + 16, _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){
cvstrncpy(end-4, 16, ".v.", _outExtensions[_outFormat], NULL);
switch (_outFormat){
case 2: // PEM format
ecc_api_key_private_save(h->verificationKey, path);
break;
default:
{
FILE * f = fopen(path, "wb");
if (f){
int len = ecc_api_key_private(h->verificationKey, NULL);
char * p = malloc(len);
ecc_api_key_private(h->verificationKey, p);
if (_outFormat == 1){ // hex format
int i;
for (i = 0; i < len; i++){
fprintf(f, "%02X", (unsigned int)p[i]);
}
}
else{
fwrite(p, 1, len, f);
}
free(p);
fclose(f);
}
}}
}
if (h->encryptionKey){
cvstrncpy(end-4, 16, ".e.", _outExtensions[_outFormat], NULL);
switch (_outFormat){
case 2: // PEM format
ecc_api_key_private_save(h->encryptionKey, path);
break;
default:
{
FILE * f = fopen(path, "wb");
if (f){
int len = ecc_api_key_private(h->encryptionKey, NULL);
char * p = malloc(len);
ecc_api_key_private(h->encryptionKey, p);
if (_outFormat == 1){ // hex format
int i;
for (i = 0; i < len; i++){
fprintf(f, "%02X", (unsigned int)p[i]);
}
}
else{
fwrite(p, 1, len, f);
}
free(p);
fclose(f);
}
}}
}
free(path);
}
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)
{
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)
{ 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;
switch(h->sa_type){
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;
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
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);
}
}
assert(h->key == NULL);
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 rc=0;
int len = cstrlen(text);
if(len){
cert_cxml_handler_t * h = (cert_cxml_handler_t *)_h;
rc = cbuf_write(text, len, &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 = 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;
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;
}
lat = strtol(v, NULL, 0);
 
v = cxml_tag_attr_value(tag, "longitude");
if(v == NULL){
fprintf(stderr, "ERROR: Longitude shall be specified for location.\n");
return -1;
}
lon = strtol(v, NULL, 0);
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{
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.pem", NULL);
key = ecc_api_key_private_load(path);
if (!key){
fprintf(stderr, "%s: Could not load issuing private key from file\n", path);
free(path);
return -1;
}
}
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;
}
}
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)
{return 0;}
/branches/Security/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)))
/branches/Security/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
/branches/Security/tools/itscertgen/cshared/copts.c
0,0 → 1,779
/*********************************************************************
######################################################################
## 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
##
######################################################################
*********************************************************************/
#include <string.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
 
#include "copts.h"
 
#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 = 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 = 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 = 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 = ((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;
}
/branches/Security/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
/branches/Security/tools/itscertgen/cshared/cserialize.c
0,0 → 1,253
#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++;
if(num_bytes > maxsize){
return -1;
}
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;
}
/branches/Security/tools/itscertgen/cshared/cserialize.h
0,0 → 1,56
#ifndef cint_h
#define cint_h
#include <stdint.h>
 
#ifdef __cplusplus
extern "C" {
#endif
 
#ifdef __GNUC__
# define cint64_swap(X) __builtin_bswap64(X)
# define cint32_swap(X) __builtin_bswap32(X)
# define cint16_swap(X) __builtin_bswap16(X)
#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
/branches/Security/tools/itscertgen/cshared/cstr.c
0,0 → 1,161
#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;
}
 
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;
}
/branches/Security/tools/itscertgen/cshared/cstr.h
0,0 → 1,40
#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);
 
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
/branches/Security/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;
}
/branches/Security/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
/branches/Security/tools/itscertgen/cxml/cxml.c
0,0 → 1,594
#include "cxml.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#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);
}
*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
/branches/Security/tools/itscertgen/cxml/cxml.h
0,0 → 1,153
#ifndef cxml_h
#define cxml_h
 
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);
 
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
/branches/Security/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++ = (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;
}
/branches/Security/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;
}
/branches/Security/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;
}
/branches/Security/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);
}
/branches/Security/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;
}
/branches/Security/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;
}
/branches/Security/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);
}
/branches/Security/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/>
/branches/Security/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>
 
/branches/Security/tools/itscertgen/ecc_api.h
0,0 → 1,36
#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;
 
void * ecc_api_key_gen (ecc_pk_algorithm pk_alg, ecc_sym_algorithm sym_alg);
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);
void * ecc_api_key_private_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
/branches/Security/tools/itscertgen/ecc_openssl.c
0,0 → 1,205
#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>
 
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_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)
{
int rc = -1;
FILE * f = fopen(path, "wb");
if(f){
rc = PEM_write_PKCS8PrivateKey(f, key, NULL, NULL, 0, _pass_cb, NULL);
fclose(f);
if(!rc){
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);
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;
}
/branches/Security/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
/branches/Security/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_
/branches/Security/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;
}
/branches/Security/tools/itscertgen
Property changes:
Added: svn:ignore
## -0,0 +1 ##
+mingw32-d