<commit_before>"""
Various helper functions for nsi2 protocol stack.

Author: <NAME> <<EMAIL>>
Copyright: NORDUnet (2012)
"""

from xml.etree import ElementTree as ET

from twisted.python import log

from opennsa import constants as cnt, nsa, error
from opennsa.shared.xmlhelper import createXMLTime, parseXMLTimestamp # these were moved
from opennsa.protocols.shared import minisoap
from opennsa.protocols.nsi2.bindings import nsiframework, nsiconnection, p2pservices


LOG_SYSTEM = 'NSI2.Helper'

# don't really fit anywhere, consider cramming them into the bindings
FRAMEWORK_TYPES_NS   = "http://schemas.ogf.org/nsi/2013/12/framework/types"
FRAMEWORK_HEADERS_NS = "http://schemas.ogf.org/nsi/2013/12/framework/headers"
CONNECTION_TYPES_NS  = "http://schemas.ogf.org/nsi/2013/12/connection/types"
SERVICE_TYPES_NS     = 'http://schemas.ogf.org/nsi/2013/12/services/types'
P2PSERVICES_TYPES_NS = 'http://schemas.ogf.org/nsi/2013/12/services/point2point'

URN_NETWORK = 'urn:ogf:network:'

ET.register_namespace('ftypes', FRAMEWORK_TYPES_NS)
ET.register_namespace('header', FRAMEWORK_HEADERS_NS)
ET.register_namespace('ctypes', CONNECTION_TYPES_NS)
ET.register_namespace('stypes', SERVICE_TYPES_NS)
ET.register_namespace('p2psrv', P2PSERVICES_TYPES_NS)

# Lookup table for urn label
LABEL_MAP = {
    'vlan' : cnt.ETHERNET_VLAN
}



def createHeader(requester_nsa_urn, provider_nsa_urn, session_security_attrs=None, reply_to=None, correlation_id=None,
                 session_security_attributes=None, connection_trace=None):

    ssats = []
    if session_security_attributes:
        for at, av in session_security_attributes:
            at = nsiframework.AttributeType(at, None, None, av)
            ssats.append( nsiframework.SessionSecurityAttrType( [ at ] ) )

    header = nsiframework.CommonHeaderType(cnt.CS2_SERVICE_TYPE, correlation_id, requester_nsa_urn, provider_nsa_urn, reply_to, ssats, connection_trace)
    header_element = header.xml(nsiframework.nsiHeader)
    return header_element


def createGenericAcknowledgement(header):

    soap_header = nsiframework.CommonHeaderType(cnt.CS2_SERVICE_TYPE, header.correlation_id, header.requester_nsa, header.provider_nsa, None, header.session_security_attrs)
    soap_header_element = soap_header.xml(nsiframework.nsiHeader)

    generic_confirm = nsiconnection.GenericAcknowledgmentType()
    generic_confirm_element = generic_confirm.xml(nsiconnection.acknowledgment)

    payload = minisoap.createSoapPayload(generic_confirm_element, soap_header_element)
    return payload


def createServiceException(err, provider_nsa, connection_id=None, service_type=None):

    variables = None
    child_exception = None

    if err.check(error.NSIError):
        error_id = err.value.errorId
        #se = bindings.ServiceExceptionType(provider_nsa, connection_id, err.value.errorId, err.getErrorMessage(), variables, child_exception)
    else:
        log.msg('Got a non NSIError exception: %s : %s' % (err.value.__class__.__name__, err.getErrorMessage()), system=LOG_SYSTEM)
        log.msg('Cannot create detailed service exception, defaulting to NSI InternalServerError (00500)', system=LOG_SYSTEM)
        log.err(err)
        error_id = error.InternalServerError.errorId
        #se = bindings.ServiceExceptionType(provider_nsa, connection_id, error.InternalServerError.errorId, err.getErrorMessage(), variables, child_exception)

    se = nsiframework.ServiceExceptionType(provider_nsa, connection_id, service_type, error_id, err.getErrorMessage(), variables, child_exception)

    return se


def parseRequest(soap_data):

    headers, bodies = minisoap.parseSoapPayload(soap_data)

    if headers is None:
        raise ValueError('No header specified in payload')
    elif len(headers) > 1:
        raise ValueError('Multiple headers specified in payload')

    header = nsiframework.parseElement(headers[0])
    #if header.protocolVersion != cnt.CS2_SERVICE_TYPE:
    #    raise ValueError('Invalid protocol "%s". Only %s supported' % (header.protocolVersion, cnt.CS2_SERVICE_TYPE))

    if len(bodies) == 0:
        body = None
    elif len(bodies) == 1:
        body = nsiconnection.parseElement(bodies[0])
    else:
        body = [ nsiconnection.parseElement(b) for b in bodies ]

    nsi_header = nsa.NSIHeader(header.requesterNSA, header.providerNSA, header.correlationId, header.replyTo, connection_trace=header.connectionTrace)

    return nsi_header, body


def parseLabel(label_part):
    if not '=' in label_part:
        raise error.PayloadError('No = in urn label part (%s)' % label_part)

    label_short_type, label_value = label_part.split('=')
    try:
        label_type = LABEL_MAP[label_short_type]
    except KeyError:
        raise error.PayloadError('Label type %s not recognized')

    return nsa.Label(label_type, label_value)


<commit_msg>parse security attributes in helper so they are given to aggregator<commit_after>"""
Various helper functions for nsi2 protocol stack.

Author: <NAME> <<EMAIL>>
Copyright: NORDUnet (2012)
"""

from xml.etree import ElementTree as ET

from twisted.python import log

from opennsa import constants as cnt, nsa, error
from opennsa.shared.xmlhelper import createXMLTime, parseXMLTimestamp # these were moved
from opennsa.protocols.shared import minisoap
from opennsa.protocols.nsi2.bindings import nsiframework, nsiconnection, p2pservices


LOG_SYSTEM = 'NSI2.Helper'

# don't really fit anywhere, consider cramming them into the bindings
FRAMEWORK_TYPES_NS   = "http://schemas.ogf.org/nsi/2013/12/framework/types"
FRAMEWORK_HEADERS_NS = "http://schemas.ogf.org/nsi/2013/12/framework/headers"
CONNECTION_TYPES_NS  = "http://schemas.ogf.org/nsi/2013/12/connection/types"
SERVICE_TYPES_NS     = 'http://schemas.ogf.org/nsi/2013/12/services/types'
P2PSERVICES_TYPES_NS = 'http://schemas.ogf.org/nsi/2013/12/services/point2point'

URN_NETWORK = 'urn:ogf:network:'

ET.register_namespace('ftypes', FRAMEWORK_TYPES_NS)
ET.register_namespace('header', FRAMEWORK_HEADERS_NS)
ET.register_namespace('ctypes', CONNECTION_TYPES_NS)
ET.register_namespace('stypes', SERVICE_TYPES_NS)
ET.register_namespace('p2psrv', P2PSERVICES_TYPES_NS)

# Lookup table for urn label
LABEL_MAP = {
    'vlan' : cnt.ETHERNET_VLAN
}



def createHeader(requester_nsa_urn, provider_nsa_urn, session_security_attrs=None, reply_to=None, correlation_id=None,
                 session_security_attributes=None, connection_trace=None):

    ssats = []
    if session_security_attributes:
        for at, av in session_security_attributes:
            at = nsiframework.AttributeType(at, None, None, av)
            ssats.append( nsiframework.SessionSecurityAttrType( [ at ] ) )

    header = nsiframework.CommonHeaderType(cnt.CS2_SERVICE_TYPE, correlation_id, requester_nsa_urn, provider_nsa_urn, reply_to, ssats, connection_trace)
    header_element = header.xml(nsiframework.nsiHeader)
    return header_element


def createGenericAcknowledgement(header):

    soap_header = nsiframework.CommonHeaderType(cnt.CS2_SERVICE_TYPE, header.correlation_id, header.requester_nsa, header.provider_nsa, None, header.session_security_attrs)
    soap_header_element = soap_header.xml(nsiframework.nsiHeader)

    generic_confirm = nsiconnection.GenericAcknowledgmentType()
    generic_confirm_element = generic_confirm.xml(nsiconnection.acknowledgment)

    payload = minisoap.createSoapPayload(generic_confirm_element, soap_header_element)
    return payload


def createServiceException(err, provider_nsa, connection_id=None, service_type=None):

    variables = None
    child_exception = None

    if err.check(error.NSIError):
        error_id = err.value.errorId
        #se = bindings.ServiceExceptionType(provider_nsa, connection_id, err.value.errorId, err.getErrorMessage(), variables, child_exception)
    else:
        log.msg('Got a non NSIError exception: %s : %s' % (err.value.__class__.__name__, err.getErrorMessage()), system=LOG_SYSTEM)
        log.msg('Cannot create detailed service exception, defaulting to NSI InternalServerError (00500)', system=LOG_SYSTEM)
        log.err(err)
        error_id = error.InternalServerError.errorId
        #se = bindings.ServiceExceptionType(provider_nsa, connection_id, error.InternalServerError.errorId, err.getErrorMessage(), variables, child_exception)

    se = nsiframework.ServiceExceptionType(provider_nsa, connection_id, service_type, error_id, err.getErrorMessage(), variables, child_exception)

    return se


def parseRequest(soap_data):

    headers, bodies = minisoap.parseSoapPayload(soap_data)

    if headers is None:
        raise ValueError('No header specified in payload')
    elif len(headers) > 1:
        raise ValueError('Multiple headers specified in payload')

    header = nsiframework.parseElement(headers[0])
    security_attributes = []
    if header.sessionSecurityAttr:
        for ssa in header.sessionSecurityAttr:
            for attr in ssa.Attributes:
                security_attributes.append( (attr.Name, attr.AttributeValue) )

    #if header.protocolVersion != cnt.CS2_SERVICE_TYPE:
    #    raise ValueError('Invalid protocol "%s". Only %s supported' % (header.protocolVersion, cnt.CS2_SERVICE_TYPE))

    if len(bodies) == 0:
        body = None
    elif len(bodies) == 1:
        body = nsiconnection.parseElement(bodies[0])
    else:
        body = [ nsiconnection.parseElement(b) for b in bodies ]

    nsi_header = nsa.NSIHeader(header.requesterNSA, header.providerNSA, header.correlationId, header.replyTo,
                               session_security_attrs=security_attributes, connection_trace=header.connectionTrace)

    return nsi_header, body


def parseLabel(label_part):
    if not '=' in label_part:
        raise error.PayloadError('No = in urn label part (%s)' % label_part)

    label_short_type, label_value = label_part.split('=')
    try:
        label_type = LABEL_MAP[label_short_type]
    except KeyError:
        raise error.PayloadError('Label type %s not recognized')

    return nsa.Label(label_type, label_value)



{'fraction_non_alphanumeric': 0.09459728867623604, 'fraction_numerical': 0.011164274322169059, 'mean_word_length': 4.6018983807928535, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '950279', 'n_tokens_mistral': 3264, 'n_tokens_neox': 3118, 'n_words': 635}