Commit a5e10368 authored by canterburym's avatar canterburym
Browse files

Update check_asn1

parent 8f69f5cb
Loading
Loading
Loading
Loading
Loading
+87 −9
Original line number Diff line number Diff line
from asn1tools import parse_files, ParseError
import sys
import logging

from asn1tools import parse_files, compile_dict, ParseError, CompileError
from glob import glob
from pathlib import Path

from pprint import pprint


def parseASN1File (asnFile):
    try:
        parse_files(asnFile)
    except ParseError as ex:
        return [ex]
    return []


def parseASN1Files (fileList):
    if len(fileList) == 0:
        logging.warning ("No files specified")
        return {}
    errors = {}
    logging.info("Parsing files...")
    for f in fileList:
        ex = parseASN1File(f)
        if ex: 
            logging.info (f"  {f}: Failed - {ex!r}")
        else: 
            logging.info (f"  {f}: OK")            
        errors[f] = ex
    return errors

schemaFileGlob = glob("*.asn1")
for schemaFile in schemaFileGlob:

def compileASN1Files (fileList):
    logging.info("Compiling files...")
    errors = []
    try:
        print("Checking file: {0}".format(schemaFile), end="")
        parse_files(schemaFile)
        print(" OK")
        d = parse_files(fileList)
        for modulename, module in d.items():
            # Weird fix because the compiler doesn't like RELATIVE-OID as a type
            # Not sure if the on-the-wire encoding would be affected or not
            # but for most checking purposes this doesn't matter
            module['types']["RELATIVE-OID"] = {'type' : 'OBJECT IDENTIFIER'}
        c = compile_dict(d)
    except CompileError as ex:
        logging.info (f"Compiler  error: {ex}")
        errors.append(ex)
    except ParseError as ex:
        sys.exit("ASN1 parser error: " + str(ex))
        logging.info (f"Parse error: {ex}")
        errors.append(ex)
    logging.info ("Compiled OK")
    return errors


def validateASN1Files (fileList):
    parseErrors = parseASN1Files(fileList)
#    if len(parseErrors > 0):
#        logging.info ("Abandonding compile due to parse errors")
    compileErrors = compileASN1Files(fileList)
    return parseErrors, compileErrors


def validateAllASN1FilesInPath (path):
    globPattern = str(Path(path)) + '/**/*.asn1'
    logging.info("Searching: " + globPattern)
    schemaGlob = glob(globPattern, recursive=True)
    return validateASN1Files(schemaGlob)    


if __name__ == '__main__':
    parseErrors, compileErrors = validateAllASN1FilesInPath("checkasn/test")
    parseErrorCount = 0
    print ("Parser checks:")
    print ("-----------------------------")
    for filename, errors in parseErrors.items():
        if len(errors) > 0:
            parseErrorCount += len(errors)
            print (f"{filename}: {len(errors)} errors")
            for error in errors:
                print ("  " + str(error))
        else:
            print (f"{filename}: OK")
    print ("-----------------------------")
    print ("Compilation:")
    print ("-----------------------------")
    if len(compileErrors) > 0:
        for error in compileErrors:            
            print ("  " + str(error))
    else:
        print ("Compilation OK")
    print ("-----------------------------")
    print (f"{parseErrorCount} parse errors, {len(compileErrors)} compile errors")
    exit (parseErrorCount + len(compileErrors))
print ("{0} ASN.1 schemas checked".format(len(schemaFileGlob)))