diff --git a/ccsrc/Externals/LibItsSecurity_externals.cc b/ccsrc/Externals/LibItsSecurity_externals.cc index c995049f6ea1b5d35a479df01debcefa6ebe68c9..7424b8edd8b5e4662cef466dfdd8f33fa63601bf 100644 --- a/ccsrc/Externals/LibItsSecurity_externals.cc +++ b/ccsrc/Externals/LibItsSecurity_externals.cc @@ -547,6 +547,21 @@ namespace LibItsSecurity__Functions return os; } + OCTETSTRING fx__test__encrypt__aes__128__gcm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt) { + loggers::get_instance().log(">>> fx__test__encrypt__aes__128__gcm__test"); + + security_ecc ec(ec_elliptic_curves::nist_p_256); + OCTETSTRING enc_message; + if (ec.encrypt(encryption_algotithm::aes_128_gcm, p__k, p__n, p__pt, enc_message) == -1) { + loggers::get_instance().warning("fx__test__encrypt__aes__128__gcm__test: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + OCTETSTRING os(enc_message + ec.tag()); + loggers::get_instance().log_msg("fx__test__encrypt__aes__128__gcm__test: encrypted message: ", os); + + return os; + } + /** * \fn OCTETSTRING fx__test__decrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__ct); * \brief Encrypt the message using AES 128 CCM algorithm @@ -593,39 +608,39 @@ namespace LibItsSecurity__Functions * \see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf */ // TODO Use common function for both fx__encryptWithEciesxxx and fx__decryptWithEciesxxx function - OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyCompressed, const INTEGER& p__compressedMode, OCTETSTRING& p__publicEphemeralKeyCompressed, INTEGER& p__ephemeralCompressedMode, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce) { + OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyCompressed, const INTEGER& p__compressedMode, const OCTETSTRING& p__salt, OCTETSTRING& p__publicEphemeralKeyCompressed, INTEGER& p__ephemeralCompressedMode, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce) { loggers::get_instance().log_msg(">>> fx__encryptWithEciesNistp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__toBeEncryptedSecuredMessage); loggers::get_instance().log_msg(">>> fx__encryptWithEciesNistp256WithSha256: p__recipientsPublicKeyCompressed", p__recipientsPublicKeyCompressed); loggers::get_instance().log(">>> fx__encryptWithEciesNistp256WithSha256: p__compressedMode: %d", static_cast(p__compressedMode)); + loggers::get_instance().log_msg(">>> fx__encryptWithEciesNistp256WithSha256: p__salt", p__salt); - // 1. Generate new Private/Public key + // 1. Generate new Private/Public Ephemeral key security_ecc ec(ec_elliptic_curves::nist_p_256); if (ec.generate() == -1) { loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate ephemeral keys"); return OCTETSTRING(0, nullptr); } - // 2. Generate and derive shared secret + // 2. Generate and derive shared secret based on recipient's private keys security_ecc ec_comp(ec_elliptic_curves::nist_p_256, p__recipientsPublicKeyCompressed, (static_cast(p__compressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y()) == -1) { + if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), p__salt) == -1) { loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate and derive secret key"); return OCTETSTRING(0, nullptr); } // Set the encrypted symmetric key + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Symmetric encryption key: ", ec.symmetric_encryption_key()); p__encrypted__sym__key = ec.encrypted_symmetric_key(); - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", p__encrypted__sym__key); + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); // Set the tag of the symmetric key encryption p__authentication__vector = ec.tag(); loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__authentication__vector: ", p__authentication__vector); // Set ephemeral public keys p__publicEphemeralKeyCompressed = ec.public_key_compressed(); - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Ephemeral public compressed key: ", p__publicEphemeralKeyCompressed); + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed); p__ephemeralCompressedMode = (ec.public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) ? 0 : 1; - loggers::get_instance().log("fx__encryptWithEciesNistp256WithSha256: Ephemeral public compressed mode: %d", p__ephemeralCompressedMode); + loggers::get_instance().log("fx__encryptWithEciesNistp256WithSha256: p__ephemeralCompressedMode: %d", p__ephemeralCompressedMode); // 3. Retrieve AES 128 parameters p__nonce = ec.nonce(); loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__nonce: ", p__nonce); - OCTETSTRING enc_symm_key = ec.symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: enc_symm_key: ", enc_symm_key); // 4. Encrypt the data using AES-128 CCM OCTETSTRING enc_message; if (ec.encrypt(encryption_algotithm::aes_128_ccm, ec.symmetric_encryption_key(), ec.nonce(), p__toBeEncryptedSecuredMessage, enc_message) == -1) { @@ -637,7 +652,50 @@ namespace LibItsSecurity__Functions return enc_message; } - + + /** + * @desc Test function for ECIES NIST P-256 Encryption with SHA-256 + * @remark For the purpose of testing, the content of p__toBeEncryptedSecuredMessage is the AES 128 symmetric key to be encrypted + */ + OCTETSTRING fx__test__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__privateEphemeralKey, const OCTETSTRING& p__recipientPublicKeyX, const OCTETSTRING& p__recipientPublicKeyY, const OCTETSTRING& p__salt, OCTETSTRING& p__publicEphemeralKeyX, OCTETSTRING& p__publicEphemeralKeyY, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce) { + + // 1. Generate new ephemeral Private/Public keys + security_ecc ec(ec_elliptic_curves::nist_p_256, p__privateEphemeralKey); + p__publicEphemeralKeyX = ec.public_key_x(); + p__publicEphemeralKeyY = ec.public_key_y(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: Vx=", p__publicEphemeralKeyX); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: Vy=", p__publicEphemeralKeyY); + + // 2. Generate and derive shared secret + security_ecc ec_comp(ec_elliptic_curves::nist_p_256, p__recipientPublicKeyX, p__recipientPublicKeyY); + ec.symmetric_encryption_key(p__toBeEncryptedSecuredMessage); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: ", ec.encrypted_symmetric_key()); + if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), p__salt) == -1) { + loggers::get_instance().warning("fx__test__encryptWithEciesNistp256WithSha256: Failed to generate and derive secret key"); + return OCTETSTRING(0, nullptr); + } + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: symmetric_encryption_key: ", ec.symmetric_encryption_key()); + // Set the encrypted symmetric key + p__encrypted__sym__key = ec.encrypted_symmetric_key(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); + // Set the tag of the symmetric key encryption + p__authentication__vector = ec.tag(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: p__authentication__vector: ", p__authentication__vector); + // 3. Retrieve AES 128 parameters + p__nonce = ec.nonce(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: p__nonce: ", p__nonce); + // 4. Encrypt the data using AES-128 CCM + OCTETSTRING enc_message; + if (ec.encrypt(encryption_algotithm::aes_128_ccm, ec.symmetric_encryption_key(), ec.nonce(), p__toBeEncryptedSecuredMessage, enc_message) == -1) { + loggers::get_instance().warning("fx__test__encryptWithEciesNistp256WithSha256: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + enc_message += ec.tag(); + loggers::get_instance().log_to_hexa("fx__test__encryptWithEciesNistp256WithSha256: enc message||Tag: ", enc_message); + + return enc_message; + } + /** * \fn OCTETSTRING fx__decryptWithEciesNistp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyX, const OCTETSTRING& p__publicEphemeralKeyY, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce); * \brief Decrypt the message using ECIES algorithm to decrypt AES 128 CCM symmetric key, as defined in IEEE Std 1609.2-2017 @@ -654,7 +712,7 @@ namespace LibItsSecurity__Functions * \see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf */ // TODO Use common function for both fx__encryptWithEciesxxx and fx__decryptWithEciesxxx function - OCTETSTRING fx__decryptWithEciesNistp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyCompressed, const INTEGER& p__ephemeralCompressedMode, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce) { + OCTETSTRING fx__decryptWithEciesNistp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyCompressed, const INTEGER& p__ephemeralCompressedMode, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce, const OCTETSTRING& p__salt) { loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__encryptedSecuredMessage); loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__privateEncKey: ", p__privateEncKey); loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed); @@ -662,13 +720,14 @@ namespace LibItsSecurity__Functions loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__nonce: ", p__nonce); loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__authentication__vector: ", p__authentication__vector); loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__salt", p__salt); - // 1. Create security_ecc instance + // 1. Create security_ecc instance based on recipient's private key security_ecc ec(ec_elliptic_curves::nist_p_256, p__privateEncKey); security_ecc ec_comp(ec_elliptic_curves::nist_p_256, p__publicEphemeralKeyCompressed, (static_cast(p__ephemeralCompressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - // 2. Generate the shared secret value based on recipient's public ephemeral keys will be required - if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p__privateEncKey, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector) == -1) { + // 2. Generate the shared secret value based on public ephemeral keys will be required + if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector, p__salt) == -1) { loggers::get_instance().warning("fx__decryptWithEciesNistp256WithSha256: Failed to generate shared secret"); return OCTETSTRING(0, nullptr); } @@ -693,7 +752,7 @@ namespace LibItsSecurity__Functions loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256WithSha256: p__recipientsPublicKeyCompressed: ", p__recipientsPublicKeyCompressed); loggers::get_instance().log(">>> fx__encryptWithEciesBrainpoolp256WithSha256: p__compressedMode: %d", static_cast(p__compressedMode)); - // 1. Generate new Private/Public key + // 1. Generate new ephemeral Private/Public keys security_ecc ec(ec_elliptic_curves::brainpool_p_256_r1); if (ec.generate() == -1) { loggers::get_instance().warning(": Failed to generate ephemeral keys"); @@ -701,7 +760,7 @@ namespace LibItsSecurity__Functions } // 2. Generate and derive shared secret security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__recipientsPublicKeyCompressed, (static_cast(p__compressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y()) == -1) { + if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), OCTETSTRING(0, nullptr)) == -1) { loggers::get_instance().warning(": Failed to generate and derive secret key"); return OCTETSTRING(0, nullptr); } @@ -742,12 +801,12 @@ namespace LibItsSecurity__Functions loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__authentication__vector: ", p__authentication__vector); loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); - // 1. Create security_ecc instance + // 1. Create security_ecc instance based on public ephemeral keys security_ecc ec(ec_elliptic_curves::brainpool_p_256_r1, p__privateEncKey); security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__publicEphemeralKeyCompressed, (static_cast(p__ephemeralCompressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - // 2. Generate the shared secret value based on recipient's public ephemeral keys will be required - if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p__privateEncKey, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector) == -1) { + // 2. Generate the shared secret value based on public ephemeral keys will be required + if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector, OCTETSTRING(0, nullptr)) == -1) { loggers::get_instance().warning("fx__decryptWithEciesBrainpoolp256WithSha256: Failed to generate shared secret"); return OCTETSTRING(0, nullptr); } diff --git a/ccsrc/Protocols/Http/http_codec.cc b/ccsrc/Protocols/Http/http_codec.cc index e0e29d8895608438eeddb184d9dd1e738302c309..dc20310c8222211e0a560e4b46fe183bcfb5165d 100644 --- a/ccsrc/Protocols/Http/http_codec.cc +++ b/ccsrc/Protocols/Http/http_codec.cc @@ -399,10 +399,14 @@ int http_codec::encode_body(const LibItsHttp__MessageBodyTypes::HttpMessageBody& loggers::get_instance().log("http_codec::encode_body: Call '%s'", it->first.c_str()); _codecs["http_its"]->encode((Record_Type&)binary_body.ieee1609dot2__data(), p_encoding_buffer); // TODO Use params - // TODO Encode in hex string + +#if !defined(GEMALTO_FIX) + // GEMALTO Encode in hex string CHARSTRING buf = oct2str(p_encoding_buffer); p_encoding_buffer = OCTETSTRING(buf.lengthof(), (const unsigned char*)(static_cast(buf))); loggers::get_instance().log_msg("http_codec::encode_body: Convert binary to string: ", p_encoding_buffer); +#endif + processed = true; } @@ -472,6 +476,16 @@ int http_codec::decode_body(TTCN_Buffer& decoding_buffer, LibItsHttp__MessageBod OCTETSTRING s(decoding_buffer.get_len() - decoding_buffer.get_pos(), decoding_buffer.get_data() + decoding_buffer.get_pos()); loggers::get_instance().log_msg("http_codec::decode_body: raw body=", s); + + +#if !defined(GEMALTO_FIX) + // GEMALTO Encode in hex string + s = str2oct(CHARSTRING(s.lengthof(), (const char*)(static_cast(s)))); + loggers::get_instance().log_msg("http_codec::decode_body: Convert string to binary: ", s); +#endif + + + // Align the payload length with the specified Content-lenght value loggers::get_instance().log("http_codec::decode_body: _dc.length=%d - body length=%d", _dc.length, s.lengthof()); OCTETSTRING body; diff --git a/ccsrc/Protocols/Security/hmac.hh b/ccsrc/Protocols/Security/hmac.hh index 28b86d68fa5f947aa78d7e130d9ab5a146d8777d..65b75a2909d0b82572ba1ba02abe323b35bc041b 100644 --- a/ccsrc/Protocols/Security/hmac.hh +++ b/ccsrc/Protocols/Security/hmac.hh @@ -51,7 +51,7 @@ public: * \param[out] p_hmac The HMAC value based of the provided data * \return 0 on success, -1 otherwise */ - int generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING& p_hmac); + int generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING& p_hmac); // TODO Use reference & /*! * \fn int generate(const unsigned char* p_buffer, const size_t p_buffer_length, const unsigned char* p_secret_key, const size_t p_secret_key_length, OCTETSTRING& p_hmac); diff --git a/ccsrc/Protocols/Security/security_ecc.cc b/ccsrc/Protocols/Security/security_ecc.cc index 26e2d968492209eeebe0decba78df6554b8c6bdf..85890fe3499dbaa540bda905383dc8c130a69943 100644 --- a/ccsrc/Protocols/Security/security_ecc.cc +++ b/ccsrc/Protocols/Security/security_ecc.cc @@ -13,6 +13,8 @@ #include #include +#include "sha256.hh" + #include "hmac.hh" #include "security_ecc.hh" @@ -103,6 +105,7 @@ security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTE } } ::EC_POINT_free(ec_point); + loggers::get_instance().log_msg("security_ecc::security_ecc (1): _pri_key=", _pri_key); loggers::get_instance().log_msg("security_ecc::security_ecc (1): _pub_key_x=", _pub_key_x); loggers::get_instance().log_msg("security_ecc::security_ecc (1): _pub_key_y=", _pub_key_y); loggers::get_instance().log_msg("security_ecc::security_ecc (1): _pub_key_compressed=", _pub_key_compressed); @@ -331,8 +334,11 @@ int security_ecc::generate() { return 0; } -int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_recipients_public_key_x, const OCTETSTRING& p_recipients_public_key_y) { - loggers::get_instance().log(">>> security_ecc::generate_and_derive_ephemeral_key (1)"); +int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_recipients_public_key_x, const OCTETSTRING& p_recipients_public_key_y, const OCTETSTRING& p_salt) { + loggers::get_instance().log(">>> security_ecc::generate_and_derive_ephemeral_key (1): %d", p_enc_algorithm); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (1): p_recipients_public_key_x=", p_recipients_public_key_x); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (1): p_recipients_public_key_y=", p_recipients_public_key_y); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (1): p_salt=", p_salt); // Sanity checks if (_pri_key.lengthof() == 0) { @@ -347,6 +353,7 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p // Set buffers size int len = (EC_GROUP_get_degree(_ec_group) + 7) / 8; + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (1): _secret_key len:%d", len); _secret_key = int2oct(0, len); unsigned int nonce_length; unsigned int sym_key_length; @@ -363,15 +370,18 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Unsupported encryption algorithm"); return -1; } // End of 'switch' statement - unsigned int k_length; + unsigned int k_enc; + unsigned int k_mac; switch (_elliptic_curve) { case ec_elliptic_curves::nist_p_256: // Use the ANSI X9.62 Prime 256v1 curve // No break; case ec_elliptic_curves::brainpool_p_256_r1: - k_length = 32; + k_enc = 16; + k_mac = 32; break; case ec_elliptic_curves::brainpool_p_384_r1: - k_length = 48; + k_enc = 24; // TODO To be checked + k_mac = 48; break; default: loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Unsupported encryption algorithm"); @@ -381,8 +391,13 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p // Convert the ephemeral public encryption keys to an EC point EC_POINT *ec_point = nullptr; bin_to_ec_point(p_recipients_public_key_x, p_recipients_public_key_y, &ec_point); - // Generate the shared secret key - int result = ::ECDH_compute_key((unsigned char*)static_cast(_secret_key), _secret_key.lengthof(), ec_point, _ec_key, nullptr); + // Generate the shared secret key (Key Agreement) + int result = ::ECDH_compute_key( + (unsigned char*)static_cast(_secret_key), + _secret_key.lengthof(), + ec_point, // From sender's public key + _ec_key, // From recipient's private key + nullptr); if (result == -1) { loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Failed to generate shared secret key"); ::EC_POINT_free(ec_point); @@ -392,45 +407,65 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _secret_key: ", _secret_key); // Derive the shared secret key - const int k_enc = nonce_length + sym_key_length + tag_length; - const int k_mac = k_length + k_length; - OCTETSTRING digest = int2oct(0, k_enc + k_mac); - loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (1): k_enc size:%d - k_mac size: %d - digest size:%d: ", k_enc, k_mac, digest.lengthof()); - if (PKCS5_PBKDF2_HMAC((const char*)static_cast(_secret_key), _secret_key.lengthof(), nullptr, 0, 2000, EVP_sha256(), digest.lengthof(), (unsigned char*)static_cast(digest)) != 1) { + OCTETSTRING digest; + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (1): k_enc size:%d - k_mac size: %d", k_enc, k_mac); + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (1): salt length:%d", p_salt.lengthof()); + if (kdf2(_secret_key, p_salt, 0x00/*sha256*/, k_enc + k_mac, digest) != 0) { loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key: Failed to derive shared secret key"); return -1; } loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): digest: ", digest); - // Extract AES 128 parameters - _nonce = OCTETSTRING(nonce_length, static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _nonce: ", _nonce); - _sym_key = OCTETSTRING(sym_key_length, _nonce.lengthof() + static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _sym_key: ", _sym_key); - _tag = OCTETSTRING(tag_length, _nonce.lengthof() + + _sym_key.lengthof() + static_cast(digest)); // TODO Useless??? - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _tag: ", _tag); - // Extract the HMAC key - OCTETSTRING hmac_secret = OCTETSTRING(k_length + k_length, nonce_length + sym_key_length + tag_length + static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): hmac_secret: ", hmac_secret); - - // Encrypt the _sym_key - if (encrypt(encryption_algotithm::aes_128_ccm, _sym_key, _nonce, _sym_key, _enc_sym_key) == -1) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Failed to encrypt key"); - return -1; + // Extract K1 and generate encrypted symmetric key + OCTETSTRING k1(k_enc, static_cast(digest)); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): k1: ", k1); + if (!_sym_key.is_bound()) { // Generate random AES 128 key + BIGNUM* r = ::BN_new(); + ::BN_pseudo_rand(r, k_enc * 8, -1, 0); + _sym_key = int2oct(0, k_enc); + ::BN_bn2bin(r, (unsigned char*)static_cast(_sym_key)); + ::BN_free(r); } + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _sym_key: ", _sym_key); + _enc_sym_key = k1 ^ _sym_key; loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): Encrypted symmetric key: ", encrypted_symmetric_key()); + // Extract K2 and generate Tag vector + OCTETSTRING k2(k_enc * 2, k_enc + static_cast(digest)); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): k2: ", k2); + hmac hmac_256; + _tag = int2oct(0, tag_length); + hmac_256.generate(static_cast(_enc_sym_key), _enc_sym_key.lengthof(), static_cast(k2), k2.lengthof(), _tag); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _tag: ", _tag); + + // Generate random IV (nonce + BIGNUM* r = ::BN_new(); + ::BN_pseudo_rand(r, k_enc * 8, -1, 0); + _nonce = int2oct(0, k_enc); + ::BN_bn2bin(r, (unsigned char*)static_cast(_nonce)); + ::BN_free(r); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _nonce: ", _nonce); + return 0; } -int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_ephemeral_public_key_x, const OCTETSTRING& p_ephemeral_public_key_y, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector) { - loggers::get_instance().log(">>> security_ecc::generate_and_derive_ephemeral_key (2)"); - +int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_ephemeral_public_key_x, const OCTETSTRING& p_ephemeral_public_key_y, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector, const OCTETSTRING& p_salt) { + loggers::get_instance().log(">>> security_ecc::generate_and_derive_ephemeral_key (2): %d", p_enc_algorithm); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_ephemeral_public_key_x", p_ephemeral_public_key_x); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_ephemeral_public_key_y", p_ephemeral_public_key_y); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_enc_sym_key", p_enc_sym_key); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_expected_nonce", p_expected_nonce); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_authentication_vector", p_authentication_vector); + loggers::get_instance().log_msg(">>> security_ecc::generate_and_derive_ephemeral_key (2): p_salt", p_salt); + // Sanity checks - if (_pri_key.lengthof() == 0) { + if ((_pub_key_x.lengthof() == 0) || (_pub_key_y.lengthof() == 0)) { loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Key shall be generated"); return -1; } + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _pub_key_x", _pub_key_x); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _pub_key_y", _pub_key_y); + _encryption_algotithm = p_enc_algorithm; _nonce = p_expected_nonce; _enc_sym_key = p_enc_sym_key; @@ -438,6 +473,7 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p // Set buffers size int len = (EC_GROUP_get_degree(_ec_group) + 7) / 8; + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (2): _secret_key len:%d", len); _secret_key = int2oct(0, len); unsigned int nonce_length; unsigned int sym_key_length; @@ -454,15 +490,16 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); return -1; } // End of 'switch' statement - unsigned int k_length; + unsigned int k_enc; + unsigned int k_mac; switch (_elliptic_curve) { case ec_elliptic_curves::nist_p_256: // Use the ANSI X9.62 Prime 256v1 curve // No break; case ec_elliptic_curves::brainpool_p_256_r1: - k_length = 32; + k_enc = 16; + k_mac = 32; break; case ec_elliptic_curves::brainpool_p_384_r1: - k_length = 48; break; default: loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); @@ -470,11 +507,18 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p } // End of 'switch' statement // Convert the peer public encryption key to an EC point + security_ecc ec(ec_elliptic_curves::nist_p_256, p_ephemeral_public_key_x, p_ephemeral_public_key_y); EC_POINT *ec_point = nullptr; - bin_to_ec_point(p_ephemeral_public_key_x, p_ephemeral_public_key_y, &ec_point); + bin_to_ec_point(ec.public_key_x(), ec.public_key_y(), &ec_point); // EC_POINT from recipient's private key // Generate the shared symmetric key - int result = ::ECDH_compute_key((unsigned char*)static_cast(_secret_key), _secret_key.lengthof(), ec_point, _ec_key, nullptr); + int result = ::ECDH_compute_key( + (unsigned char*)static_cast(_secret_key), + _secret_key.lengthof(), + ec_point, // From recipient's private key + _ec_key, // From sender's public key + nullptr); if (result == -1) { + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Failed to compute shared secret key"); ::EC_POINT_free(ec_point); return -1; } @@ -482,54 +526,36 @@ int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _secret_key: ", _secret_key); // Derive the shared secret key - const int k_enc = nonce_length + sym_key_length + tag_length; - const int k_mac = k_length + k_length; - OCTETSTRING digest = int2oct(0, k_enc + k_mac); - loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (2): k_enc size:%d - k_mac size: %d - digest size:%d: ", k_enc, k_mac, digest.lengthof()); - if (PKCS5_PBKDF2_HMAC((const char*)static_cast(_secret_key), _secret_key.lengthof(), nullptr, 0, 2000, EVP_sha256(), digest.lengthof(), (unsigned char*)static_cast(digest)) != 1) { + OCTETSTRING digest; + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (2): k_enc size:%d - k_mac size: %d", k_enc, k_mac); + loggers::get_instance().log("security_ecc::generate_and_derive_ephemeral_key (2): salt length:%d", p_salt.lengthof()); + if (kdf2(_secret_key, p_salt, 0x00, k_enc + k_mac, digest) != 0) { loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key: Failed to derive shared secret key"); return -1; } loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): digest: ", digest); - // Extract AES 128 parameters - OCTETSTRING nonce(nonce_length, static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): Generated nonce: ", nonce); - OCTETSTRING sym_key(sym_key_length, nonce.lengthof() + static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): sym_key: ", sym_key); - OCTETSTRING tag(tag_length, nonce.lengthof() + sym_key.lengthof() + static_cast(digest)); // TODO Useless??? - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): tag: ", tag); - // Extract the HMAC key - OCTETSTRING hmac_secret(k_length + k_length, nonce_length + sym_key_length + tag_length + static_cast(digest)); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): hmac_secret: ", hmac_secret); - - // Check if nonce vectors are valid - if (_nonce != nonce) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Failed to derive nonce vector"); - return -1; - } - - // Decrypt the symmetric key - OCTETSTRING skey; - if (decrypt(p_enc_algorithm, sym_key, nonce, p_authentication_vector, p_enc_sym_key, skey) == -1) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Failed to decrypt key"); - return -1; - } - _sym_key = skey; + // Extract K2 and generate Tag vector + OCTETSTRING k2(k_enc * 2, k_enc + static_cast(digest)); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): k2: ", k2); + hmac hmac_256; + _tag = int2oct(0, tag_length); + hmac_256.generate(static_cast(_enc_sym_key), _enc_sym_key.lengthof(), static_cast(k2), k2.lengthof(), _tag); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _tag: ", _tag); + + // Extract K1 and generate encrypted symmetric key + OCTETSTRING k1(k_enc, static_cast(digest)); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): k1: ", k1); + _sym_key = p_enc_sym_key ^ k1; loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): Decrypted symmetric key: ", symmetric_encryption_key()); return 0; } -int security_ecc::generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_recipients_compressed_key_x, const INTEGER& p_compressed_mode, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector) { - loggers::get_instance().log(">>> security_ecc::generate_and_derive_ephemeral_key (3)"); - - security_ecc ec(ec_elliptic_curves::nist_p_256, p_recipients_compressed_key_x, (p_compressed_mode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); // FIXME Why using ec_elliptic_curves::nist_p_256, it can be brainpool_p_256_r1 - return generate_and_derive_ephemeral_key(p_enc_algorithm, p_private_enc_key, ec.public_key_x(), ec.public_key_y(), p_enc_sym_key, p_expected_nonce, p_authentication_vector); -} - int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_message, OCTETSTRING& p_enc_message) { loggers::get_instance().log(">>> security_ecc::encrypt: %d", p_enc_algorithm); + loggers::get_instance().log_msg(">>> security_ecc::encrypt: p_message=", p_message); + loggers::get_instance().log_msg(">>> security_ecc::encrypt: p_enc_message=", p_enc_message); // Sanity checks if ((_pub_key_x.lengthof() != 0) || (_pub_key_y.lengthof() != 0)) { @@ -540,6 +566,7 @@ int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTE // Initialize the context and encryption operation EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); + unsigned int ctr_set_iv_len, ctr_set_tag, ctr_get_tag; switch (_encryption_algotithm) { case encryption_algotithm::aes_128_ccm: ::EVP_EncryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); @@ -548,15 +575,32 @@ int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTE _tag = int2oct(0, 16); _sym_key = int2oct(0, 16); p_enc_message = int2oct(0, p_message.lengthof()); + ctr_set_iv_len = EVP_CTRL_CCM_SET_IVLEN; + ctr_set_tag = EVP_CTRL_CCM_SET_TAG; + ctr_get_tag = EVP_CTRL_CCM_GET_TAG; break; case encryption_algotithm::aes_256_ccm: ::EVP_EncryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); + ctr_set_iv_len = EVP_CTRL_CCM_SET_IVLEN; + ctr_set_tag = EVP_CTRL_CCM_SET_TAG; + ctr_get_tag = EVP_CTRL_CCM_GET_TAG; break; case encryption_algotithm::aes_128_gcm: ::EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); + // Allocate buffers size + _nonce = int2oct(0, 12); + _tag = int2oct(0, 16); + _sym_key = int2oct(0, 16); + p_enc_message = int2oct(0, p_message.lengthof()); + ctr_set_iv_len = EVP_CTRL_GCM_SET_IVLEN; + ctr_set_tag = EVP_CTRL_GCM_SET_TAG; + ctr_get_tag = EVP_CTRL_GCM_GET_TAG; break; case encryption_algotithm::aes_256_gcm: ::EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); + ctr_set_iv_len = EVP_CTRL_GCM_SET_IVLEN; + ctr_set_tag = EVP_CTRL_GCM_SET_TAG; + ctr_get_tag = EVP_CTRL_GCM_GET_TAG; break; } // End of 'switch' statement // Generate _sym_key @@ -566,9 +610,9 @@ int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTE ::RAND_bytes((unsigned char*)static_cast(_nonce), _nonce.lengthof()); loggers::get_instance().log_msg("security_ecc::encrypt: nonce: ", _nonce); // Set nonce length - ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, _nonce.lengthof(), nullptr); + ::EVP_CIPHER_CTX_ctrl(ctx, ctr_set_iv_len, _nonce.lengthof(), nullptr); // Set tag length - ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, _tag.lengthof(), nullptr); + ::EVP_CIPHER_CTX_ctrl(ctx, ctr_set_tag, _tag.lengthof(), nullptr); // Prime the key and nonce ::EVP_EncryptInit_ex(ctx, nullptr, nullptr, static_cast(_sym_key), static_cast(_nonce)); // No authentication data @@ -578,7 +622,7 @@ int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTE // Finalize the encryption session ::EVP_EncryptFinal_ex(ctx, (unsigned char*)static_cast(p_enc_message) + len, &len); // Get the authentication tag(const char*)static_cast( - ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_GET_TAG, _tag.lengthof(), (unsigned char*)static_cast(_tag)); + ::EVP_CIPHER_CTX_ctrl(ctx, ctr_get_tag, _tag.lengthof(), (unsigned char*)static_cast(_tag)); loggers::get_instance().log_msg("security_ecc::encrypt: tag: ", _tag); ::EVP_CIPHER_CTX_free(ctx); @@ -858,3 +902,51 @@ int security_ecc::public_key_to_bin(OCTETSTRING& p_bin_key) { // ec_key_public_k return 0; } + +int security_ecc::kdf2(const OCTETSTRING& p_secret_key, const OCTETSTRING& p_salt, const unsigned char p_hash_algorithm, const int p_key_length, OCTETSTRING& p_digest) { + loggers::get_instance().log(">>> security_ecc::kdf2"); + + // Sanity checks + + int result = -1; + switch (p_hash_algorithm) { + case 0x00: // SHA 256 + result = kdf2_sha256(p_secret_key, p_salt, p_key_length, p_digest); + break; + } // End of 'switch' statement + + + return result; +} + +int security_ecc::kdf2_sha256(const OCTETSTRING& p_secret_key, const OCTETSTRING& p_salt, const int p_key_length, OCTETSTRING& p_digest) { + loggers::get_instance().log_msg(">>> security_ecc::kdf2_sha256: p_secret_key: ", p_secret_key); + loggers::get_instance().log_msg(">>> security_ecc::kdf2_sha256: p_salt: ", p_salt); + loggers::get_instance().log(">>> security_ecc::kdf2_sha256: p_key_length:%d", p_key_length); + + // Sanity checks + + + int sha256_blk_len = 32; + int num_blk_out = (int)ceil(p_key_length/(float)sha256_blk_len); + loggers::get_instance().log("security_ecc::kdf2_sha256: num_blk_out= %d", num_blk_out); + p_digest = OCTETSTRING(0, nullptr); + sha256 hash; + for (int i = 1; i < num_blk_out + 1; i++) { + OCTETSTRING hash_input = p_secret_key + int2oct(i, 4) + p_salt; + loggers::get_instance().log_msg("security_ecc::kdf2_sha256: hash_input: ", hash_input); + OCTETSTRING h; + hash.generate(hash_input, h); + loggers::get_instance().log_msg("security_ecc::kdf2_sha256: h: ", h); + p_digest += h; + loggers::get_instance().log_msg("security_ecc::kdf2_sha256: p_digest: ", p_digest); + loggers::get_instance().log("security_ecc::kdf2_sha256: p_digest: %d", p_digest.lengthof()); + } // End of 'for' statement + if (p_digest.lengthof() > p_key_length * 2) { + p_digest = OCTETSTRING(p_key_length * 2, static_cast(p_digest)); + } + + loggers::get_instance().log_msg("<<< security_ecc::kdf2_sha256: p_secret_key: ", p_digest); + return 0; +} + diff --git a/ccsrc/Protocols/Security/security_ecc.hh b/ccsrc/Protocols/Security/security_ecc.hh index 928d73fee141a020ccd9021d8b7de5254ca4d2fe..61aab3ea21e15547abd12aa6676f24586fd473ec 100644 --- a/ccsrc/Protocols/Security/security_ecc.hh +++ b/ccsrc/Protocols/Security/security_ecc.hh @@ -128,7 +128,7 @@ public: //! \publicsection /*! * \fn int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_recipients_public_key_x, const OCTETSTRING& p_recipients_public_key_y); * \brief Generate a shared secret key and derive it using KDF2 algorithm. - * This method shall be used by the sender. Fresh keys will be genrated for each cyphering operation + * This method shall be used for encryption, fresh keys will be genrated for each cyphering operation * \param[in] p_enc_algorithm The encryption algorithm to be used * \param[in] p_recipients_public_key_x The recipient public key X-coordinate * \param[in] p_recipients_public_key_x The recipient public key Y-coordinate @@ -138,21 +138,20 @@ public: //! \publicsection * \see encrypt methog to encrypt a message based of the generated symetric encryption key * \return 0 on success, -1 otherwise */ - int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_recipients_public_key_x, const OCTETSTRING& p_recipients_public_key_y); + int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_recipients_public_key_x, const OCTETSTRING& p_recipients_public_key_y, const OCTETSTRING& p_salt); /*! * \fn int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_ephemeral_public_key_x, const OCTETSTRING& p_ephemeral_public_key_y); * \brief Generate a shared secret key and derive it using KDF2 algorithm. + * This method shall be used for decryption process * \param[in] p_enc_algorithm The encryption algorithm to be used - * \param[in] p_private_enc_key The private encryption key associated to the public encryption key * \param[in] p_ephemeral_public_key_x The recipient public key X-coordinate - * \param[in] p_ephemeral_public_key_x The recipient public key Y-coordinate + * \param[in] p_ephemeral_public_key_y The recipient public key Y-coordinate * \remark To get the secret key, uses \see secret_key method * \remark To get the decrypteded symmetric encryption key, uses \see symmetric_encryption_key method * \return 0 on success, -1 otherwise */ - int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_ephemeral_public_key_x, const OCTETSTRING& p_ephemeral_public_key_y, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector); - int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_recipients_compressed_key_x, const INTEGER& p_compressed_mode, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector); + int generate_and_derive_ephemeral_key(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_ephemeral_public_key_x, const OCTETSTRING& p_ephemeral_public_key_y, const OCTETSTRING& p_enc_sym_key, const OCTETSTRING& p_expected_nonce, const OCTETSTRING& p_authentication_vector, const OCTETSTRING& p_salt); /*! * \fn int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_message, OCTETSTRING& p_enc_message); @@ -217,6 +216,13 @@ public: //! \publicsection inline const OCTETSTRING& encryption_key_y() const { return _enc_key_y; }; inline const OCTETSTRING& encrypted_symmetric_key() const { return _enc_sym_key; }; inline const OCTETSTRING& symmetric_encryption_key() const { return _sym_key; }; + /*! + * \fn void symmetric_encryption_key(const OCTETSTRING& p_sym_key); + * \brief Set AES symmetric key value. + * To be used for test purpose only + * \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES + */ + inline void symmetric_encryption_key(const OCTETSTRING& p_sym_key) { _sym_key = p_sym_key; }; inline const OCTETSTRING& nonce() const { return _nonce; }; inline const OCTETSTRING& tag() const { return _tag; }; @@ -240,10 +246,6 @@ private: //! \privatesection */ int public_key_to_bin(OCTETSTRING& p_bin_key); - /*int multiply_point_with_bn(const EC_POINT &a, const BIGNUM* b, EC_POINT **P); - // R: XY-coordinate compressed, S: Share Secret - int derive_s_from_private_key(BIGNUM *S, BIGNUM *R); - // R: XY-coordinate compressed, S: Share Secret - int derive_s_from_public_key(BIGNUM *S, BIGNUM *R);*/ - + int kdf2(const OCTETSTRING& p_secret_key, const OCTETSTRING& p_salt, const unsigned char p_hash_algorithm, const int p_key_length, OCTETSTRING& p_digest); + int kdf2_sha256(const OCTETSTRING& p_secret_key, const OCTETSTRING& p_salt, const int p_key_length, OCTETSTRING& p_digest); }; // End of class security_ecc diff --git a/ccsrc/Protocols/Security/security_services.cc b/ccsrc/Protocols/Security/security_services.cc index 81af5993b325f394a02aa52df086e573e677f25e..c71c6d82cde9821375f9999bac7f105b03393b29 100644 --- a/ccsrc/Protocols/Security/security_services.cc +++ b/ccsrc/Protocols/Security/security_services.cc @@ -383,16 +383,16 @@ int security_services::process_ieee_1609_dot2_encrypted_data(const IEEE1609dot2: } // 3. Generate the shared secret value based on recipient's public ephemeral keys will be required - security_ecc ec(ec_elliptic_curves::nist_p_256, p_enc_key); int result; + security_ecc ec(ec_elliptic_curves::nist_p_256, p_enc_key); if (ecies->v().ischosen(IEEE1609dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p_enc_key, ecies->v().uncompressedP256().x(), ecies->v().uncompressedP256().y(), ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t()); + result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ecies->v().uncompressedP256().x(), ecies->v().uncompressedP256().y(), ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t(), OCTETSTRING(0, nullptr)); } else if (ecies->v().ischosen(IEEE1609dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - const INTEGER compressed_mode(0); - result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p_enc_key, ecies->v().compressed__y__0(), compressed_mode, ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t()); + security_ecc ec_comp(ec_elliptic_curves::nist_p_256, ecies->v().compressed__y__0(), ecc_compressed_mode::compressed_y_0); + result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t(), OCTETSTRING(0, nullptr)); } else if(ecies->v().ischosen(IEEE1609dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - const INTEGER compressed_mode(1); - result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p_enc_key, ecies->v().compressed__y__1(), compressed_mode, ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t()); + security_ecc ec_comp(ec_elliptic_curves::nist_p_256, ecies->v().compressed__y__1(), ecc_compressed_mode::compressed_y_1); + result = ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y(), ecies->c(), p_encrypted_data.ciphertext().aes128ccm().nonce(), ecies->t(), OCTETSTRING(0, nullptr)); } else { loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to decode Decrypt Ieee1609Dot2Data-Encrypted"); return -1; @@ -592,7 +592,7 @@ int security_services::encrypt_gn_payload(const OCTETSTRING& p_unsecured_gn_payl } // 3. Generate and derive shared secret - if (_ec_keys_enc.get()->generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, r_public_key_x, r_public_key_y) == -1) { + if (_ec_keys_enc.get()->generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, r_public_key_x, r_public_key_y, OCTETSTRING(0, nullptr)) == -1) { loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to generate and derive secret key"); return -1; } diff --git a/docker/run-container.sh b/docker/run-container.sh index 161beaa18cce0a5f2a191b23bb666d7dae463ddb..5f1cffa87ebe913f210aec520b787690a102c513 100755 --- a/docker/run-container.sh +++ b/docker/run-container.sh @@ -5,7 +5,7 @@ #set -e set -vx -docker run -i --rm stf525_its:latest /bin/bash #-c "sudo etsi" +docker run -i --rm stf525_its:latest /bin/bash -c "cd /home/etsi/dev/etsi_its/src/TestCodec/objs && ../bin/run_all.bash" # That's all Floks exit 0 diff --git a/etc/TestCodec/TestCodec.cfg b/etc/TestCodec/TestCodec.cfg index abdc2df1b1b8a1cd607e1e3f0964a67dd4e34a20..615d9b9aaeeb020eea3aa101350e35ddeedf7284 100644 --- a/etc/TestCodec/TestCodec.cfg +++ b/etc/TestCodec/TestCodec.cfg @@ -285,7 +285,7 @@ system.pkiPort.params := "PKI/HTTP(device_mode=1,uri=/its/inner_ec_request,host= #TestCodec_SecuredFuntions.tc_sha384_1 #TestCodec_SecuredFuntions.tc_f_generate_key_pair_1 #TestCodec_SecuredFuntions.tc_f_generate_key_pair_2 -TestCodec_SecuredFuntions.tc_f_generate_key_pair_3 +#TestCodec_SecuredFuntions.tc_f_generate_key_pair_3 #TestCodec_SecuredFuntions.tc_f_signWithEcdsaNistp256WithSha256_1 #TestCodec_SecuredFuntions.tc_f_verifyWithEcdsaNistp256WithSha256_1 #TestCodec_SecuredFuntions.tc_f_verifyWithEcdsaNistp256WithSha256_2 @@ -327,12 +327,17 @@ TestCodec_SecuredFuntions.tc_f_generate_key_pair_3 #TestCodec_SecuredFuntions.tc_read_certificate_digest #TestCodec_SecuredFuntions.tc_read_certificate_hash # Encryption -#TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test1 -#TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test2 -#TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test3 -#TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_1 -#TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_2 -#TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_3 +TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test1 +TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test2 +TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test3 +TestCodec_SignedAndEncryptedMessages.tc_test_hmac_sha256_test4 +TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_1 +TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_2 +TestCodec_SignedAndEncryptedMessages.tc_test_encrypt_aes_128_ccm_test_3 +TestCodec_SignedAndEncryptedMessages.tc_test_encryptWithEciesNistp256WithSha256_1 +TestCodec_SignedAndEncryptedMessages.tc_test_encryptWithEciesNistp256WithSha256_2 +TestCodec_SignedAndEncryptedMessages.tc_test_encryptWithEciesNistp256WithSha256_3 +TestCodec_SignedAndEncryptedMessages.tc_test_encryptWithEciesNistp256WithSha256_4 #TestCodec_SignedAndEncryptedMessages.tc_encrypted_signed_message_1 #TestCodec_SignedAndEncryptedMessages.tc_decrypted_signed_message_2 #TestCodec_SignedAndEncryptedMessages.tc_decrypted_signed_message_3 diff --git a/javasrc/CeCILL-C LICENSE.txt b/javasrc/CeCILL-C LICENSE.txt deleted file mode 100644 index cfe9f1dd72da53c582710a544ef02006f0ade583..0000000000000000000000000000000000000000 --- a/javasrc/CeCILL-C LICENSE.txt +++ /dev/null @@ -1,516 +0,0 @@ -CeCILL-C FREE SOFTWARE LICENSE AGREEMENT - - - Notice - -This Agreement is a Free Software license agreement that is the result -of discussions between its authors in order to ensure compliance with -the two main principles guiding its drafting: - - * firstly, compliance with the principles governing the distribution - of Free Software: access to source code, broad rights granted to - users, - * secondly, the election of a governing law, French law, with which - it is conformant, both as regards the law of torts and - intellectual property law, and the protection that it offers to - both authors and holders of the economic rights over software. - -The authors of the CeCILL-C (for Ce[a] C[nrs] I[nria] L[ogiciel] L[ibre]) -license are: - -Commissariat à l'Energie Atomique - CEA, a public scientific, technical -and industrial research establishment, having its principal place of -business at 25 rue Leblanc, immeuble Le Ponant D, 75015 Paris, France. - -Centre National de la Recherche Scientifique - CNRS, a public scientific -and technological establishment, having its principal place of business -at 3 rue Michel-Ange, 75794 Paris cedex 16, France. - -Institut National de Recherche en Informatique et en Automatique - -INRIA, a public scientific and technological establishment, having its -principal place of business at Domaine de Voluceau, Rocquencourt, BP -105, 78153 Le Chesnay cedex, France. - - - Preamble - -The purpose of this Free Software license agreement is to grant users -the right to modify and re-use the software governed by this license. - -The exercising of this right is conditional upon the obligation to make -available to the community the modifications made to the source code of -the software so as to contribute to its evolution. - -In consideration of access to the source code and the rights to copy, -modify and redistribute granted by the license, users are provided only -with a limited warranty and the software's author, the holder of the -economic rights, and the successive licensors only have limited liability. - -In this respect, the risks associated with loading, using, modifying -and/or developing or reproducing the software by the user are brought to -the user's attention, given its Free Software status, which may make it -complicated to use, with the result that its use is reserved for -developers and experienced professionals having in-depth computer -knowledge. Users are therefore encouraged to load and test the -suitability of the software as regards their requirements in conditions -enabling the security of their systems and/or data to be ensured and, -more generally, to use and operate it in the same conditions of -security. This Agreement may be freely reproduced and published, -provided it is not altered, and that no provisions are either added or -removed herefrom. - -This Agreement may apply to any or all software for which the holder of -the economic rights decides to submit the use thereof to its provisions. - - - Article 1 - DEFINITIONS - -For the purpose of this Agreement, when the following expressions -commence with a capital letter, they shall have the following meaning: - -Agreement: means this license agreement, and its possible subsequent -versions and annexes. - -Software: means the software in its Object Code and/or Source Code form -and, where applicable, its documentation, "as is" when the Licensee -accepts the Agreement. - -Initial Software: means the Software in its Source Code and possibly its -Object Code form and, where applicable, its documentation, "as is" when -it is first distributed under the terms and conditions of the Agreement. - -Modified Software: means the Software modified by at least one -Integrated Contribution. - -Source Code: means all the Software's instructions and program lines to -which access is required so as to modify the Software. - -Object Code: means the binary files originating from the compilation of -the Source Code. - -Holder: means the holder(s) of the economic rights over the Initial -Software. - -Licensee: means the Software user(s) having accepted the Agreement. - -Contributor: means a Licensee having made at least one Integrated -Contribution. - -Licensor: means the Holder, or any other individual or legal entity, who -distributes the Software under the Agreement. - -Integrated Contribution: means any or all modifications, corrections, -translations, adaptations and/or new functions integrated into the -Source Code by any or all Contributors. - -Related Module: means a set of sources files including their -documentation that, without modification to the Source Code, enables -supplementary functions or services in addition to those offered by the -Software. - -Derivative Software: means any combination of the Software, modified or -not, and of a Related Module. - -Parties: mean both the Licensee and the Licensor. - -These expressions may be used both in singular and plural form. - - - Article 2 - PURPOSE - -The purpose of the Agreement is the grant by the Licensor to the -Licensee of a non-exclusive, transferable and worldwide license for the -Software as set forth in Article 5 hereinafter for the whole term of the -protection granted by the rights over said Software. - - - Article 3 - ACCEPTANCE - -3.1 The Licensee shall be deemed as having accepted the terms and -conditions of this Agreement upon the occurrence of the first of the -following events: - - * (i) loading the Software by any or all means, notably, by - downloading from a remote server, or by loading from a physical - medium; - * (ii) the first time the Licensee exercises any of the rights - granted hereunder. - -3.2 One copy of the Agreement, containing a notice relating to the -characteristics of the Software, to the limited warranty, and to the -fact that its use is restricted to experienced users has been provided -to the Licensee prior to its acceptance as set forth in Article 3.1 -hereinabove, and the Licensee hereby acknowledges that it has read and -understood it. - - - Article 4 - EFFECTIVE DATE AND TERM - - - 4.1 EFFECTIVE DATE - -The Agreement shall become effective on the date when it is accepted by -the Licensee as set forth in Article 3.1. - - - 4.2 TERM - -The Agreement shall remain in force for the entire legal term of -protection of the economic rights over the Software. - - - Article 5 - SCOPE OF RIGHTS GRANTED - -The Licensor hereby grants to the Licensee, who accepts, the following -rights over the Software for any or all use, and for the term of the -Agreement, on the basis of the terms and conditions set forth hereinafter. - -Besides, if the Licensor owns or comes to own one or more patents -protecting all or part of the functions of the Software or of its -components, the Licensor undertakes not to enforce the rights granted by -these patents against successive Licensees using, exploiting or -modifying the Software. If these patents are transferred, the Licensor -undertakes to have the transferees subscribe to the obligations set -forth in this paragraph. - - - 5.1 RIGHT OF USE - -The Licensee is authorized to use the Software, without any limitation -as to its fields of application, with it being hereinafter specified -that this comprises: - - 1. permanent or temporary reproduction of all or part of the Software - by any or all means and in any or all form. - - 2. loading, displaying, running, or storing the Software on any or - all medium. - - 3. entitlement to observe, study or test its operation so as to - determine the ideas and principles behind any or all constituent - elements of said Software. This shall apply when the Licensee - carries out any or all loading, displaying, running, transmission - or storage operation as regards the Software, that it is entitled - to carry out hereunder. - - - 5.2 RIGHT OF MODIFICATION - -The right of modification includes the right to translate, adapt, -arrange, or make any or all modifications to the Software, and the right -to reproduce the resulting software. It includes, in particular, the -right to create a Derivative Software. - -The Licensee is authorized to make any or all modification to the -Software provided that it includes an explicit notice that it is the -author of said modification and indicates the date of the creation thereof. - - - 5.3 RIGHT OF DISTRIBUTION - -In particular, the right of distribution includes the right to publish, -transmit and communicate the Software to the general public on any or -all medium, and by any or all means, and the right to market, either in -consideration of a fee, or free of charge, one or more copies of the -Software by any means. - -The Licensee is further authorized to distribute copies of the modified -or unmodified Software to third parties according to the terms and -conditions set forth hereinafter. - - - 5.3.1 DISTRIBUTION OF SOFTWARE WITHOUT MODIFICATION - -The Licensee is authorized to distribute true copies of the Software in -Source Code or Object Code form, provided that said distribution -complies with all the provisions of the Agreement and is accompanied by: - - 1. a copy of the Agreement, - - 2. a notice relating to the limitation of both the Licensor's - warranty and liability as set forth in Articles 8 and 9, - -and that, in the event that only the Object Code of the Software is -redistributed, the Licensee allows effective access to the full Source -Code of the Software at a minimum during the entire period of its -distribution of the Software, it being understood that the additional -cost of acquiring the Source Code shall not exceed the cost of -transferring the data. - - - 5.3.2 DISTRIBUTION OF MODIFIED SOFTWARE - -When the Licensee makes an Integrated Contribution to the Software, the -terms and conditions for the distribution of the resulting Modified -Software become subject to all the provisions of this Agreement. - -The Licensee is authorized to distribute the Modified Software, in -source code or object code form, provided that said distribution -complies with all the provisions of the Agreement and is accompanied by: - - 1. a copy of the Agreement, - - 2. a notice relating to the limitation of both the Licensor's - warranty and liability as set forth in Articles 8 and 9, - -and that, in the event that only the object code of the Modified -Software is redistributed, the Licensee allows effective access to the -full source code of the Modified Software at a minimum during the entire -period of its distribution of the Modified Software, it being understood -that the additional cost of acquiring the source code shall not exceed -the cost of transferring the data. - - - 5.3.3 DISTRIBUTION OF DERIVATIVE SOFTWARE - -When the Licensee creates Derivative Software, this Derivative Software -may be distributed under a license agreement other than this Agreement, -subject to compliance with the requirement to include a notice -concerning the rights over the Software as defined in Article 6.4. -In the event the creation of the Derivative Software required modification -of the Source Code, the Licensee undertakes that: - - 1. the resulting Modified Software will be governed by this Agreement, - 2. the Integrated Contributions in the resulting Modified Software - will be clearly identified and documented, - 3. the Licensee will allow effective access to the source code of the - Modified Software, at a minimum during the entire period of - distribution of the Derivative Software, such that such - modifications may be carried over in a subsequent version of the - Software; it being understood that the additional cost of - purchasing the source code of the Modified Software shall not - exceed the cost of transferring the data. - - - 5.3.4 COMPATIBILITY WITH THE CeCILL LICENSE - -When a Modified Software contains an Integrated Contribution subject to -the CeCILL license agreement, or when a Derivative Software contains a -Related Module subject to the CeCILL license agreement, the provisions -set forth in the third item of Article 6.4 are optional. - - - Article 6 - INTELLECTUAL PROPERTY - - - 6.1 OVER THE INITIAL SOFTWARE - -The Holder owns the economic rights over the Initial Software. Any or -all use of the Initial Software is subject to compliance with the terms -and conditions under which the Holder has elected to distribute its work -and no one shall be entitled to modify the terms and conditions for the -distribution of said Initial Software. - -The Holder undertakes that the Initial Software will remain ruled at -least by this Agreement, for the duration set forth in Article 4.2. - - - 6.2 OVER THE INTEGRATED CONTRIBUTIONS - -The Licensee who develops an Integrated Contribution is the owner of the -intellectual property rights over this Contribution as defined by -applicable law. - - - 6.3 OVER THE RELATED MODULES - -The Licensee who develops a Related Module is the owner of the -intellectual property rights over this Related Module as defined by -applicable law and is free to choose the type of agreement that shall -govern its distribution under the conditions defined in Article 5.3.3. - - - 6.4 NOTICE OF RIGHTS - -The Licensee expressly undertakes: - - 1. not to remove, or modify, in any manner, the intellectual property - notices attached to the Software; - - 2. to reproduce said notices, in an identical manner, in the copies - of the Software modified or not; - - 3. to ensure that use of the Software, its intellectual property - notices and the fact that it is governed by the Agreement is - indicated in a text that is easily accessible, specifically from - the interface of any Derivative Software. - -The Licensee undertakes not to directly or indirectly infringe the -intellectual property rights of the Holder and/or Contributors on the -Software and to take, where applicable, vis-à-vis its staff, any and all -measures required to ensure respect of said intellectual property rights -of the Holder and/or Contributors. - - - Article 7 - RELATED SERVICES - -7.1 Under no circumstances shall the Agreement oblige the Licensor to -provide technical assistance or maintenance services for the Software. - -However, the Licensor is entitled to offer this type of services. The -terms and conditions of such technical assistance, and/or such -maintenance, shall be set forth in a separate instrument. Only the -Licensor offering said maintenance and/or technical assistance services -shall incur liability therefor. - -7.2 Similarly, any Licensor is entitled to offer to its licensees, under -its sole responsibility, a warranty, that shall only be binding upon -itself, for the redistribution of the Software and/or the Modified -Software, under terms and conditions that it is free to decide. Said -warranty, and the financial terms and conditions of its application, -shall be subject of a separate instrument executed between the Licensor -and the Licensee. - - - Article 8 - LIABILITY - -8.1 Subject to the provisions of Article 8.2, the Licensee shall be -entitled to claim compensation for any direct loss it may have suffered -from the Software as a result of a fault on the part of the relevant -Licensor, subject to providing evidence thereof. - -8.2 The Licensor's liability is limited to the commitments made under -this Agreement and shall not be incurred as a result of in particular: -(i) loss due the Licensee's total or partial failure to fulfill its -obligations, (ii) direct or consequential loss that is suffered by the -Licensee due to the use or performance of the Software, and (iii) more -generally, any consequential loss. In particular the Parties expressly -agree that any or all pecuniary or business loss (i.e. loss of data, -loss of profits, operating loss, loss of customers or orders, -opportunity cost, any disturbance to business activities) or any or all -legal proceedings instituted against the Licensee by a third party, -shall constitute consequential loss and shall not provide entitlement to -any or all compensation from the Licensor. - - - Article 9 - WARRANTY - -9.1 The Licensee acknowledges that the scientific and technical -state-of-the-art when the Software was distributed did not enable all -possible uses to be tested and verified, nor for the presence of -possible defects to be detected. In this respect, the Licensee's -attention has been drawn to the risks associated with loading, using, -modifying and/or developing and reproducing the Software which are -reserved for experienced users. - -The Licensee shall be responsible for verifying, by any or all means, -the suitability of the product for its requirements, its good working -order, and for ensuring that it shall not cause damage to either persons -or properties. - -9.2 The Licensor hereby represents, in good faith, that it is entitled -to grant all the rights over the Software (including in particular the -rights set forth in Article 5). - -9.3 The Licensee acknowledges that the Software is supplied "as is" by -the Licensor without any other express or tacit warranty, other than -that provided for in Article 9.2 and, in particular, without any warranty -as to its commercial value, its secured, safe, innovative or relevant -nature. - -Specifically, the Licensor does not warrant that the Software is free -from any error, that it will operate without interruption, that it will -be compatible with the Licensee's own equipment and software -configuration, nor that it will meet the Licensee's requirements. - -9.4 The Licensor does not either expressly or tacitly warrant that the -Software does not infringe any third party intellectual property right -relating to a patent, software or any other property right. Therefore, -the Licensor disclaims any and all liability towards the Licensee -arising out of any or all proceedings for infringement that may be -instituted in respect of the use, modification and redistribution of the -Software. Nevertheless, should such proceedings be instituted against -the Licensee, the Licensor shall provide it with technical and legal -assistance for its defense. Such technical and legal assistance shall be -decided on a case-by-case basis between the relevant Licensor and the -Licensee pursuant to a memorandum of understanding. The Licensor -disclaims any and all liability as regards the Licensee's use of the -name of the Software. No warranty is given as regards the existence of -prior rights over the name of the Software or as regards the existence -of a trademark. - - - Article 10 - TERMINATION - -10.1 In the event of a breach by the Licensee of its obligations -hereunder, the Licensor may automatically terminate this Agreement -thirty (30) days after notice has been sent to the Licensee and has -remained ineffective. - -10.2 A Licensee whose Agreement is terminated shall no longer be -authorized to use, modify or distribute the Software. However, any -licenses that it may have granted prior to termination of the Agreement -shall remain valid subject to their having been granted in compliance -with the terms and conditions hereof. - - - Article 11 - MISCELLANEOUS - - - 11.1 EXCUSABLE EVENTS - -Neither Party shall be liable for any or all delay, or failure to -perform the Agreement, that may be attributable to an event of force -majeure, an act of God or an outside cause, such as defective -functioning or interruptions of the electricity or telecommunications -networks, network paralysis following a virus attack, intervention by -government authorities, natural disasters, water damage, earthquakes, -fire, explosions, strikes and labor unrest, war, etc. - -11.2 Any failure by either Party, on one or more occasions, to invoke -one or more of the provisions hereof, shall under no circumstances be -interpreted as being a waiver by the interested Party of its right to -invoke said provision(s) subsequently. - -11.3 The Agreement cancels and replaces any or all previous agreements, -whether written or oral, between the Parties and having the same -purpose, and constitutes the entirety of the agreement between said -Parties concerning said purpose. No supplement or modification to the -terms and conditions hereof shall be effective as between the Parties -unless it is made in writing and signed by their duly authorized -representatives. - -11.4 In the event that one or more of the provisions hereof were to -conflict with a current or future applicable act or legislative text, -said act or legislative text shall prevail, and the Parties shall make -the necessary amendments so as to comply with said act or legislative -text. All other provisions shall remain effective. Similarly, invalidity -of a provision of the Agreement, for any reason whatsoever, shall not -cause the Agreement as a whole to be invalid. - - - 11.5 LANGUAGE - -The Agreement is drafted in both French and English and both versions -are deemed authentic. - - - Article 12 - NEW VERSIONS OF THE AGREEMENT - -12.1 Any person is authorized to duplicate and distribute copies of this -Agreement. - -12.2 So as to ensure coherence, the wording of this Agreement is -protected and may only be modified by the authors of the License, who -reserve the right to periodically publish updates or new versions of the -Agreement, each with a separate number. These subsequent versions may -address new issues encountered by Free Software. - -12.3 Any Software distributed under a given version of the Agreement may -only be subsequently distributed under the same version of the Agreement -or a subsequent version. - - - Article 13 - GOVERNING LAW AND JURISDICTION - -13.1 The Agreement is governed by French law. The Parties agree to -endeavor to seek an amicable solution to any disagreements or disputes -that may arise during the performance of the Agreement. - -13.2 Failing an amicable solution within two (2) months as from their -occurrence, and unless emergency proceedings are necessary, the -disagreements or disputes shall be referred to the Paris Courts having -jurisdiction, by the more diligent Party. - - -Version 1.0 dated 2006-09-05. \ No newline at end of file diff --git a/javasrc/adapter/org/etsi/adapter/GnssSupportFactory.java b/javasrc/adapter/org/etsi/adapter/GnssSupportFactory.java deleted file mode 100644 index a8944fde5badaaa77c816d7fec27e0ae3aa23278..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/adapter/GnssSupportFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Factory for GNSS Support implementations. - * Implementations have to register to this factory. - * - */ -package org.etsi.adapter; - -/** - * Factory for Test Execution Required implementations. - * Implementations have to register to this factory. - */ -public class GnssSupportFactory { - - /** - * Registered IGnssSupport implementation - */ - private static IGnssSupport instance; - - /** - * Gets the registered IGnssSupport implementation - * @return Instance of IGnssSupport implementation registered through setImpl() or null - * @see setImpl - */ - public static IGnssSupport getInstance() { - return instance; - } - - /** - * Private constructor (Singleton pattern) - */ - private GnssSupportFactory() { - //empty - } - - /** - * Sets the implementation instance to be returned by the factory - * @param impl Instance of the implementation to be registered - */ - public static void setImpl(IGnssSupport impl) { - instance = impl; - } -} diff --git a/javasrc/adapter/org/etsi/adapter/IGnssSupport.java b/javasrc/adapter/org/etsi/adapter/IGnssSupport.java deleted file mode 100644 index ea179f2d31bfff7e499c20ef5ffdec13f72feec5..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/adapter/IGnssSupport.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ---------------------------------------------------------------------------- - * (C) Copyright Testing Technologies, 2001-2015. All Rights Reserved. - * - * All copies of this program, whether in whole or in part, and whether - * modified or not, must display this and all other embedded copyright - * and ownership notices in full. - * - * See the file COPYRIGHT for details of redistribution and use. - * - * You should have received a copy of the COPYRIGHT file along with - * this file; if not, write to the Testing Technologies, - * Michaelkirchstr. 17/18, 10179 Berlin, Germany. - * - * TESTING TECHNOLOGIES DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS - * SOFTWARE. IN NO EVENT SHALL TESTING TECHNOLOGIES BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN - * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, - * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF - * THIS SOFTWARE. - * - * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, - * EITHER EXPRESSED OR IMPLIED, INCLUDING ANY KIND OF IMPLIED OR - * EXPRESSED WARRANTY OF NON-INFRINGEMENT OR THE IMPLIED WARRANTIES - * OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - * - * ----------------------------------------------------------------------------- */ -/** - * GNSS support interface to be implemented by TE providers. - */ -package org.etsi.adapter; - -import java.math.BigInteger; - -import org.etsi.its.adapter.ports.AdapterPort; -import org.etsi.ttcn.tri.TriStatus; - -/** - * Test Execution Required interface to be implemented by TE providers. - */ -public interface IGnssSupport { - - /** - * Initialize the GNSS support. - * @return TRI_OK in case of success, false otherwise - */ - public TriStatus init(); - - /** - * Loads a scenario - * @param id of predefined scenario - * @return TRUE on success, FALSE otherwise - */ - public boolean loadScenario(int p_id); - - /** - * Starts a loaded scenario - * @return TRUE on success, FALSE otherwise - */ - public boolean startScenario(); - - /** - * Stops a started scenario - * @return TRUE on success, FALSE otherwise - */ - public boolean stopScenario(); - - /** - * Signals when the requested distance was covered - * @param distance The requested distance in m. - * @return TRUE on success, FALSE otherwise - */ - public boolean awaitDistanceToCover(AdapterPort notifier, double distance); - - /** - * Changes dynamically the speed in the running scenario - * @param The new speed value. - * @return TRUE on success, FALSE otherwise - */ - public boolean changeSpeed(double speed); - - /** - * Changes dynamically the heading in the running scenario - * @param heading The new heading value. - * @return TRUE on success, FALSE otherwise - */ - public boolean changeHeading(double heading); - - /** - * Gets the current GPS time - * @return the time - */ - public BigInteger getGpsTime(); - - /** - * Signals when the requested time in the running scenario is reached - * @param time The requested time in msec. - * @return TRUE on success, FALSE otherwise - */ - public boolean awaitTimeInRunningScenario(AdapterPort notifier, int time); - - /** - * Dispose object - */ - public void dispose(); - -} diff --git a/javasrc/adapter/org/etsi/adapter/ITERequired.java b/javasrc/adapter/org/etsi/adapter/ITERequired.java deleted file mode 100644 index f663cbd319819d817702bce5fe60f21fcf51864b..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/adapter/ITERequired.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Test Execution Required interface to be implemented by TE providers. - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.adapter; - -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriAddress; -import org.etsi.ttcn.tri.TriCommunicationTE; -import org.etsi.ttcn.tri.TriMessage; -import org.etsi.ttcn.tri.TriStatus; - -/** - * Test Execution Required interface to be implemented by TE providers. - */ -public interface ITERequired { - - /** - * Gets TriCommunicationTE implementation - * @return TriCommunicationTE implementation - */ - TriCommunicationTE getCommunicationTE(); - - /** - * Creates TriStatus object corresponding to statusCode - * @param statusCode Status value - * @return TriStatus corresponding to statusCode - */ - TriStatus getTriStatus(int statusCode); - - /** - * Creates TriStatus object corresponding to statusCode (non TRI-standard) - * @param statusCode Status value - * @param message Informational message (Error cause, ...) - * @return TriStatus corresponding to statusCode - */ - TriStatus getTriStatus(int statusCode, String message); - - /** - * Gets TriAddress - * @param message - * @return TriAddress - */ - TriAddress getTriAddress(byte[] message); - - /** - * Gets TriMessage - * @param message - * @return TriMessage - */ - TriMessage getTriMessage(byte[] message); - - /** - * Gets Test Adapter configuration parameter (non TRI-standard) - * @param param Name of the configuration parameter - * @return Value associated to the TA parameter - */ - Value getTaParameter(String param); - - /** - * Logs the debug message. - */ - void logDebug(String debugMessage); - - /** - * Logs the error message. - */ - void logError(String errorMessage); - -} diff --git a/javasrc/adapter/org/etsi/adapter/TERFactory.java b/javasrc/adapter/org/etsi/adapter/TERFactory.java deleted file mode 100644 index d0b53552d48509aa654da62ac7544bd87da1bf8f..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/adapter/TERFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Factory for Test Execution Required implementations. - * Implementations have to register to this factory. - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.adapter; - -/** - * Factory for Test Execution Required implementations. - * Implementations have to register to this factory. - */ -public class TERFactory { - - /** - * Registered ITERequired implementation - */ - private static ITERequired instance; - - /** - * Gets the registered ITERequired implementation - * @return Instance of ITERequired implementation registered through setImpl() or null - * @see setImpl - */ - public static ITERequired getInstance() { - return instance; - } - - /** - * Private constructor (Singleton pattern) - */ - private TERFactory() { - //empty - } - - /** - * Sets the implementation instance to be returned by the factory - * @param impl Instance of the implementation to be registered - */ - public static void setImpl(ITERequired impl) { - instance = impl; - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ComponentMgr.java b/javasrc/adapter/org/etsi/its/adapter/ComponentMgr.java deleted file mode 100644 index 41a41a808a2edeeaa87179fddd7e545b439a2a3b..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ComponentMgr.java +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Component manager that handles ports and component creation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Observer; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ITuple; -import org.etsi.common.Tuple; -import org.etsi.its.adapter.ports.IObservable; -import org.etsi.its.adapter.ports.IPort; -import org.etsi.ttcn.tri.TriComponentId; -import org.etsi.ttcn.tri.TriPortId; - -/** - * Component manager that handles ports and component creation - */ -public class ComponentMgr{ - - /** - * Association Component ID <-> Component reference - */ - private LinkedHashMap mapCompNameToTriComp; - - /** - * Association Component ID <-> { (TTCN-3 Port reference / SUT Port reference) } - */ - private LinkedHashMap>> mapTriPortToTuple; - - /** - * Used to add Observer object - */ - private TestAdapter adapter; - - /** - * Constructor - * @param adapter TestAdapter reference, required for Observer/Observable pattern - */ - public ComponentMgr(final TestAdapter adapter) { - - this.adapter = adapter; - mapCompNameToTriComp = new LinkedHashMap(); - mapTriPortToTuple = new LinkedHashMap>>(); - } - - /** - * Adds a new component - * If the component was already added, nothing is done - * @param component The component to add - */ - public void addComponent(TriComponentId component) { - // Sanity check - if(component == null) { - TERFactory.getInstance().logError("Error: Trying to add null component"); - return; - } - - if(!mapCompNameToTriComp.containsKey(component.getComponentId())) { - // Create an entry in the list of Component - mapCompNameToTriComp.put(component.getComponentId(), component); - if(!mapTriPortToTuple.containsKey(component.getComponentId())) { - // Create an entry in the list of Component/Ports - mapTriPortToTuple.put(component.getComponentId(), new LinkedHashMap>()); - } - } - } - - /** - * Adds a new port to the specified component - * @param component The component reference - * @param portname The port name - * @param port The port to add - */ - public void addPort(final String componentName, final TriPortId ttcnPort, final IPort port) { - // Sanity checks - if(componentName.isEmpty() || (ttcnPort == null) || (port == null)) { - TERFactory.getInstance().logError("ComponentMgr.addPort: Wrong parameters"); - return; - } - if(!mapCompNameToTriComp.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.addPort: Trying to add port to unknown component"); - return; - } - if(!mapTriPortToTuple.containsKey(componentName)) { - // Create an entry in the list of Component/Ports - mapTriPortToTuple.put(componentName, new LinkedHashMap>()); - } - - Map> portItem = mapTriPortToTuple.get(componentName); - if(!portItem.containsKey(ttcnPort.getPortName())) { - portItem.put(ttcnPort.getPortName(), new Tuple(ttcnPort, port)); - ((IObservable)port).addObserver((Observer) adapter); - mapTriPortToTuple.put(componentName, portItem); - } - } - - /** - * Gets the component reference from its name - * @param componentName The component name - * @return The component reference if the component exists, null otherwise - */ - public TriComponentId getComponent(String componentName) { - - // Sanity checks - if(componentName == null || componentName.isEmpty()) { - TERFactory.getInstance().logError("ComponentMgr.getComponent: Invalid component"); - return null; - } - - return mapCompNameToTriComp.get(componentName); - } - - /** - * Retrieves the TTCN-3 port identifier (TriPortId) from component/port names - * @param componentName The component reference - * @param portName The port name - * @return The TTCN-3 port identifier if the component and the port exists, null otherwise - */ - public TriPortId getPortId(String componentName, String portName) { - - // Sanity checks - if(componentName.isEmpty() || portName.isEmpty()) { - TERFactory.getInstance().logError("ComponentMgr.getPortId: Wrong parameters"); - return null; - } - if(!mapCompNameToTriComp.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.getPortId: Unknown component"); - return null; - } - if(!mapTriPortToTuple.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.getPortId: No port list entry"); - return null; - } - - Map> portItem = mapTriPortToTuple.get(componentName); - if(!portItem.containsKey(portName)) { - return null; - } - - ITuple item = portItem.get(portName); - return item.getA(); - } - - /** - * Retrieves the test adapter port identifier (Port or IAdapterPort) from component/port names - * @param componentName The component owner - * @return The port reference if the component and the port exists, null otherwise - * - * @see Port - * @see IAdapterPort - */ - public IPort getPort(String componentName, String portName) { - - // Sanity checks - if(componentName.isEmpty() || portName.isEmpty()) { - TERFactory.getInstance().logError("ComponentMgr.getPort: Wrong parameters"); - return null; - } - if(!mapCompNameToTriComp.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.getPort: Unknown component"); - return null; - } - if(!mapTriPortToTuple.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.getPort: No port list entry"); - return null; - } - - Map> portItem = mapTriPortToTuple.get(componentName); - if(!portItem.containsKey(portName)) { - return null; - } - - ITuple item = portItem.get(portName); - return item.getB(); - } - - /** - * Removes the specified component - * - * Note that after the port removal, if the component has no more port, it will be removed also - * - * @param component The component reference - */ - public void removeComponent(String componentName) { - - removeAllPorts(); - } - - /** - * Removes the specified port - * - * Note that all ports attached to this component will be removed also - * - * @param componentName The component name to remove - */ - public void removePort(String componentName, String portName) { - - // Sanity checks - if(componentName.isEmpty() || portName.isEmpty()) { - TERFactory.getInstance().logError("ComponentMgr.removePort: Wrong parameters"); - return; - } - if(!mapCompNameToTriComp.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.removePort: Unknown component"); - return; - } - if(!mapTriPortToTuple.containsKey(componentName)) { - TERFactory.getInstance().logError("ComponentMgr.removePort: No port list entry"); - return; - } - - Map> portItem = mapTriPortToTuple.get(componentName); - if(!portItem.containsKey(portName)) { - return; - } - // Remove Observers - ((IObservable)portItem.get(portName).getB()).deleteObservers(); - - // Call dispose - ((IPort)portItem.get(portName).getB()).dispose(); - - // Remove item - portItem.remove(portName); - if(portItem.size() != 0) { - mapTriPortToTuple.put(componentName, portItem); - } else { - mapTriPortToTuple.remove(componentName); - mapCompNameToTriComp.remove(componentName); - if(mapCompNameToTriComp.isEmpty()) { - mapCompNameToTriComp.clear(); - } - } - if(mapTriPortToTuple.isEmpty()) { - mapTriPortToTuple.clear(); - } - } - - /** - * Removes all ports. - */ - public void removeAllPorts() { - - // Remove all ports - for(Object componentName : mapTriPortToTuple.keySet().toArray()) { - Map> portItem = mapTriPortToTuple.get(componentName); - for(Object portName : portItem.keySet().toArray()) { - removePort((String)componentName, (String)portName); - } - } - - // Remove component mapping - mapCompNameToTriComp.clear(); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/IManagementLayers.java b/javasrc/adapter/org/etsi/its/adapter/IManagementLayers.java deleted file mode 100644 index 920e281083b8d4904af73a147f5967196db657b8..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/IManagementLayers.java +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Management interface for protocol layers - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ - -package org.etsi.its.adapter; - -import java.math.BigInteger; - -import org.etsi.its.adapter.ports.FsapPort; -import org.etsi.its.adapter.ports.GnPort; - -/** - * Management interface for protocol layers - */ -public interface IManagementLayers { - - /** - * Gets the GeoNetworking beacon header to be sent by Test Adapter for the current component - * @return Beacon header, or null if no Beacon shall be sent - */ - public byte[] getGnBeacon(); - - /** - * Registers a GN port - */ - public void registerGnPort(GnPort gnPort); - - /** - * Registers a FSAP port - * @param The FSAP port to register - */ - public void registerFsapPort(final FsapPort fntpPort); - - - /** - * Gets the GeoNetworking beaconing interval - * @return GeoNetworking beaconing interval in ms - */ - public int getGnBeaconInterval(); - - /** - * Gets the GeoNetworking beacon header acting as filter for enqueueing Beacons received from neighbours - * @return Beacon header, or null if no Beacon shall be enqueued - */ - public byte[] getGnEnqueueBeacon(); - - /** - * Inserts or updates a neighbour position vector in Test Adapter internal tables - * @param mid Mid part of the neighbour's GN_Address - * @param timestamp Timestamp of the carrying message - * @param lpv Long position vector of the neighbour - */ - public void gnUpdateLocTable(byte[] mid, long timestamp, byte[] lpv); - - /** - * Sets the link layer address of this component - * param linkLayerAddress Link-layer address (6 bytes) - */ - public void setLinkLayerAddress(byte[] linkLayerAddress); - - /** - * Gets the link layer address of this component - * @return Link-layer address (6 bytes) - */ - public byte[] getLinkLayerAddress(); - - /** - * Gets the latitude of this component - * @return Latitude - */ - public byte[] getLatitude(); - - /** - * Gets the Longitude of this component - * @return Longitude - */ - public byte[] getLongitude(); - - /** - * Enable the secured mode - * @param securityData data required to execute the signing process on beacons - */ - public void setSecuredMode(final byte[] securityData); - - /** - * Disable the secured mode - */ - public void unsetSecuredMode(); - - /** - * In case TA shall fully support secured mode, security checks shall be applied - * Otherwise the Security ATS shall manage the security checks as part of testing - * @return true if secured mode is set, false otherwise - */ - public boolean isEnforceSecuredModeSet(); - - /** - * Gets the secured mode status - * @return true if secured mode is set, false otherwise - * - * @remark When the secured mode status is set, the TA shall at least filter secured packet to extract SOPV, LS_REQUEST and so on - */ - public boolean isSecuredModeSet(); - - /** - * Gets the private key for signing process - * @return The private key - */ - public BigInteger getSigningPrivateKey(); - - /** - * Gets the public key X for signing check - * @return The public key X - */ - public byte[] getSigningPublicKeyX(); - - /** - * Gets the public key Y for signing check - * @return The public key Y - */ - public byte[] getSigningPublicKeyY(); - - /** - * Gets the AT certificate value - * @return The AT certificate value - * @remark It shall not be used when secured mode is set by the test execution - */ - byte[] getAtCertificate(); - - /** - * Gets the Hashed8 value from the AT certificate - * @return The Hashed8 value - * @remark It shall not be used when secured mode is set by the test execution - */ - byte[] getAtCertificateDigest(); - - /** - * Requests ITS-AID for other profile - */ - int getItsAidOther(); - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/IManagementTA.java b/javasrc/adapter/org/etsi/its/adapter/IManagementTA.java deleted file mode 100644 index c1ac94f27548b467f2e0a15f0203ebefcbf64994..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/IManagementTA.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Management interface for Test Adapter main class - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ - -package org.etsi.its.adapter; - -/** - * Management interface for Test Adapter main class - */ -public interface IManagementTA { - - /** - * Requests Test Adapter to start sending periodic beacons for the current component - * @param beaconHeader Beacon to be sent (TST field will be updated) - */ - public void startBeaconing(byte[] beaconHeader); - - /** - * Requests Test Adapter to stop sending periodic beacons for the current component - */ - public void stopBeaconing(); - - /** - * Requests Test Adapter to start enqueueing beacon messages on the current component GN port - * @param beaconHeader Only messages matching this beacon header will be enqueued - */ - public void startEnqueueingBeacons(byte[] beaconHeader); - - /** - * Requests Test Adapter to stop enqueueing beacon messages on the current component GN port - */ - public void stopEnqueueingBeacons(); - - /** - * Requests Test Adapter to start simulating neighbour presence by sending multiple periodic beacons for the current component - * @param beaconHeader Beacon to be sent (TST field will be updated, GN addresses will be random) - * @param nbNeighbours Number of neighbours to simulate - */ - public void startMultipleBeaconing(byte[] beaconHeader, int nbNeighbours); - - /** - * Requests Test Adapter to stop simulating neighbour presence - */ - public void stopMultipleBeaconing(); - - /** - * Gets the long position vector of a neighbour given its GN_Address - * @param targetGnAddress GN_Address of the target neighbour - * @return Long position vector of the target neighbour as received in its last beacon, or null - */ - public byte[] getLongPositionVector(byte[] targetGnAddress); - - /** - * Requests Test Adapter to trigger a Service Provider InSapPrimitiveUp/SAM message sending - * @param sam The SAM message to transmit - */ - public void startSamTransmission(final byte[] sam); - - /** - * Requests Test Adapter to stop a Service Provider InSapPrimitiveUp/SAM message sending - * @param sam The SAM message to transmit - */ - public void stopSamTransmission(); - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/LEDataInputStream.java b/javasrc/adapter/org/etsi/its/adapter/LEDataInputStream.java deleted file mode 100644 index 6550a78ad23381570277f10ec2b192803033a835..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/LEDataInputStream.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * @(#)LEDataInputStream.java - * - * Summary: Little-Endian version of DataInputStream. - * - * Copyright: (c) 1998-2010 Roedy Green, Canadian Mind Products, http://mindprod.com - * - * Licence: This software may be copied and used freely for any purpose but military. - * http://mindprod.com/contact/nonmil.html - * - * Requires: JDK 1.1+ - * - * Created with: IntelliJ IDEA IDE. - * - * Version History: - * 1.8 2007-05-24 - */ -package org.etsi.its.adapter; - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * Little-Endian version of DataInputStream. - *

- * Very similar to DataInputStream except it reads little-endian instead of - * big-endian binary data. We can't extend DataInputStream directly since it has - * only final methods, though DataInputStream itself is not final. This forces - * us implement LEDataInputStream with a DataInputStream object, and use wrapper - * methods. - * - * @author Roedy Green, Canadian Mind Products - * @version 1.8 2007-05-24 - * @since 1998 - */ -public final class LEDataInputStream implements DataInput { - // ------------------------------ CONSTANTS ------------------------------ - - /** - * undisplayed copyright notice. - * - * @noinspection UnusedDeclaration - */ - private static final String EMBEDDED_COPYRIGHT = "copyright (c) 1999-2010 Roedy Green, Canadian Mind Products, http://mindprod.com"; - - // ------------------------------ FIELDS ------------------------------ - - /** - * to get at the big-Endian methods of a basic DataInputStream - * - * @noinspection WeakerAccess - */ - protected final DataInputStream dis; - - /** - * to get at the a basic readBytes method. - * - * @noinspection WeakerAccess - */ - protected final InputStream is; - - /** - * work array for buffering input. - * - * @noinspection WeakerAccess - */ - protected final byte[] work; - - // -------------------------- PUBLIC STATIC METHODS - // -------------------------- - - /** - * Note. This is a STATIC method! - * - * @param in - * stream to read UTF chars from (endian irrelevant) - * - * @return string from stream - * @throws IOException - * if read fails. - */ - public static String readUTF(DataInput in) throws IOException { - return DataInputStream.readUTF(in); - } - - // -------------------------- PUBLIC INSTANCE METHODS - // -------------------------- - - /** - * constructor. - * - * @param in - * binary inputstream of little-endian data. - */ - public LEDataInputStream(InputStream in) { - this.is = in; - this.dis = new DataInputStream(in); - work = new byte[8]; - } - - /** - * close. - * - * @throws IOException - * if close fails. - */ - public final void close() throws IOException { - dis.close(); - } - - /** - * Read bytes. Watch out, read may return fewer bytes than requested. - * - * @param ba - * where the bytes go. - * @param off - * offset in buffer, not offset in file. - * @param len - * count of bytes to read. - * - * @return how many bytes read. - * @throws IOException - * if read fails. - */ - public final int read(byte ba[], int off, int len) throws IOException { - // For efficiency, we avoid one layer of wrapper - return is.read(ba, off, len); - } - - /** - * read only a one-byte boolean. - * - * @return true or false. - * @throws IOException - * if read fails. - * @see java.io.DataInput#readBoolean() - */ - @Override - public final boolean readBoolean() throws IOException { - return dis.readBoolean(); - } - - /** - * read byte. - * - * @return the byte read. - * @throws IOException - * if read fails. - * @see java.io.DataInput#readByte() - */ - @Override - public final byte readByte() throws IOException { - return dis.readByte(); - } - - /** - * Read on char. like DataInputStream.readChar except little endian. - * - * @return little endian 16-bit unicode char from the stream. - * @throws IOException - * if read fails. - */ - @Override - public final char readChar() throws IOException { - dis.readFully(work, 0, 2); - return (char) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); - } - - /** - * Read a double. like DataInputStream.readDouble except little endian. - * - * @return little endian IEEE double from the datastream. - * @throws IOException - */ - @Override - public final double readDouble() throws IOException { - return Double.longBitsToDouble(readLong()); - } - - /** - * Read one float. Like DataInputStream.readFloat except little endian. - * - * @return little endian IEEE float from the datastream. - * @throws IOException - * if read fails. - */ - @Override - public final float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - /** - * Read bytes until the array is filled. - * - * @see java.io.DataInput#readFully(byte[]) - */ - @Override - public final void readFully(byte ba[]) throws IOException { - dis.readFully(ba, 0, ba.length); - } - - /** - * Read bytes until the count is satisfied. - * - * @throws IOException - * if read fails. - * @see java.io.DataInput#readFully(byte[],int,int) - */ - @Override - public final void readFully(byte ba[], int off, int len) throws IOException { - dis.readFully(ba, off, len); - } - - /** - * Read an int, 32-bits. Like DataInputStream.readInt except little endian. - * - * @return little-endian binary int from the datastream - * @throws IOException - * if read fails. - */ - @Override - public final int readInt() throws IOException { - dis.readFully(work, 0, 4); - return (work[3]) << 24 | (work[2] & 0xff) << 16 | (work[1] & 0xff) << 8 - | (work[0] & 0xff); - } - - /** - * Read a line. - * - * @return a rough approximation of the 8-bit stream as a 16-bit unicode - * string - * @throws IOException - * @noinspection deprecation - * @deprecated This method does not properly convert bytes to characters. - * Use a Reader instead with a little-endian encoding. - */ - @Deprecated - @Override - public final String readLine() throws IOException { - return dis.readLine(); - } - - /** - * read a long, 64-bits. Like DataInputStream.readLong except little endian. - * - * @return little-endian binary long from the datastream. - * @throws IOException - */ - @Override - public final long readLong() throws IOException { - dis.readFully(work, 0, 8); - return (long) (work[7]) << 56 | - /* long cast needed or shift done modulo 32 */ - (long) (work[6] & 0xff) << 48 | (long) (work[5] & 0xff) << 40 - | (long) (work[4] & 0xff) << 32 | (long) (work[3] & 0xff) << 24 - | (long) (work[2] & 0xff) << 16 | (long) (work[1] & 0xff) << 8 - | work[0] & 0xff; - } - - /** - * Read short, 16-bits. Like DataInputStream.readShort except little endian. - * - * @return little endian binary short from stream. - * @throws IOException - * if read fails. - */ - @Override - public final short readShort() throws IOException { - dis.readFully(work, 0, 2); - return (short) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); - } - - /** - * Read UTF counted string. - * - * @return String read. - */ - @Override - public final String readUTF() throws IOException { - return dis.readUTF(); - } - - /** - * Read an unsigned byte. Note: returns an int, even though says Byte - * (non-Javadoc) - * - * @throws IOException - * if read fails. - * @see java.io.DataInput#readUnsignedByte() - */ - @Override - public final int readUnsignedByte() throws IOException { - return dis.readUnsignedByte(); - } - - /** - * Read an unsigned short, 16 bits. Like DataInputStream.readUnsignedShort - * except little endian. Note, returns int even though it reads a short. - * - * @return little-endian int from the stream. - * @throws IOException - * if read fails. - */ - @Override - public final int readUnsignedShort() throws IOException { - dis.readFully(work, 0, 2); - return ((work[1] & 0xff) << 8 | (work[0] & 0xff)); - } - - /** - * Skip over bytes in the stream. See the general contract of the - * skipBytes method of DataInput. - *

- * Bytes for this operation are read from the contained input stream. - * - * @param n - * the number of bytes to be skipped. - * - * @return the actual number of bytes skipped. - * @throws IOException - * if an I/O error occurs. - */ - @Override - public final int skipBytes(int n) throws IOException { - return dis.skipBytes(n); - } -} \ No newline at end of file diff --git a/javasrc/adapter/org/etsi/its/adapter/Main.java b/javasrc/adapter/org/etsi/its/adapter/Main.java deleted file mode 100644 index bc5f5378e051f7bd69ffad6be191582b7e44bc73..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/Main.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Test and debug module. - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ - -package org.etsi.its.adapter; - -import org.etsi.its.adapter.ports.ProtocolPort; -import org.etsi.its.adapter.ports.ProtocolPortFactory; - -/** - * Test and debug module. - */ -public class Main { - - /** - * @param args - */ - public static void main(String[] args) { - - } - - /** - * Creates CAM port using stack LoopBack/Debug and sends a message - */ - @SuppressWarnings("unused") - private static void camTest() { - - ProtocolPort port = ProtocolPortFactory.getInstance().createPort("camPort", "toto", "GN/Debug", "ACACACACACAC"); - port.send("CAM MESSAGE !".getBytes()); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - port.dispose(); - } - - /** - * Creates BTP port using stack GN/LoopBack/Debug and sends a message - */ - @SuppressWarnings("unused") - private static void btpTest() { - - ProtocolPort port = ProtocolPortFactory.getInstance().createPort("btpPort", "toto", "GN/Loopback/Debug", "ACACACACACAC"); - port.send("BTP MESSAGE !".getBytes()); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - port.dispose(); - } - - /** - * Creates GN port using stack GnSource and sends a message - */ - @SuppressWarnings("unused") - private static void gnTest() { - byte[] gnMsg = {(byte)0x00, (byte)0x50, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x1f, (byte)0x00, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, (byte)0x54, (byte)0x45, (byte)0x53, (byte)0x54, (byte)0x20, (byte)0x31, (byte)0x20, (byte)0x54, (byte)0x45, (byte)0x53, (byte)0x54, (byte)0x20, - (byte)0x54, (byte)0x45, (byte)0x53, (byte)0x54, (byte)0x20, (byte)0x54, (byte)0x45, (byte)0x53, (byte)0x54, (byte)0x20, (byte)0x54, (byte)0x45, (byte)0x53, (byte)0x54, (byte)0x20, (byte)0x54, - (byte)0x45, (byte)0x53, (byte)0x54}; - - ProtocolPort port = ProtocolPortFactory.getInstance().createPort("geoNetworkingPort", "toto", "Loopback/Debug", "ACACACACACAC"); - port.send(gnMsg); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - port.dispose(); - - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/Management.java b/javasrc/adapter/org/etsi/its/adapter/Management.java deleted file mode 100644 index fd79ff9c73f98925ecd575f51aac294663d1181a..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/Management.java +++ /dev/null @@ -1,481 +0,0 @@ -/** - * This class is used to centralise test adapter configuration and execution parameters - * All settings are component specific (multiton) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ - -package org.etsi.its.adapter; - -import java.io.ByteArrayOutputStream; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.etsi.adapter.TERFactory; -import org.etsi.certificates.CertificatesIOFactory; -import org.etsi.certificates.io.ICertificatesIO; -import org.etsi.common.ByteHelper; -import org.etsi.common.ITuple; -import org.etsi.common.Tuple; -import org.etsi.its.adapter.ports.FsapPort; -import org.etsi.its.adapter.ports.GnPort; -import org.etsi.ttcn.tci.CharstringValue; - -import de.fraunhofer.sit.c2x.CryptoLib; - -/** - * This class is used to centralise test adapter configuration and execution parameters - * All settings are component specific (multiton) - */ -public class Management implements IManagementTA, IManagementLayers { - - /** - * Instances of Management - */ - private static final ConcurrentMap instances = new ConcurrentHashMap(); - - /** - * GeoNetworking beaconning interval - */ - private static final int GN_BEACON_INTERVAL = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("TsBeaconInterval")).getString()); - - /** - * Maximum time for getting Long position vector (in seconds) - */ - private static final int GET_LPV_TIMEOUT = 10; //FIXME: Might be a parameter rather than a constant - - /** - * Interval for polling the location table during GetLpv (in ms) - */ - private static final long GET_LPV_POLL_INTERVAL = 1000; - - /** - * Test system latitude - */ - private static final int latitude = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("TsLatitude")).getString()); - - /** - * Test system longitude - */ - private static final int longitude = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("TsLongitude")).getString()); - - /** - * Enforce secured mode status - */ - //private static String TsEnforceSecuredMode = ((CharstringValue)TERFactory.getInstance().getTaParameter("TsEnforceSecuredMode")).getString(); - private static String TsEnforceSecuredMode = "false"; - - /** - * Secured root path to access certificates & private keys - */ - private static final String TsSecuredRootPath = ((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredRootPath")).getString(); - - /** - * Secured configuration identifier - */ - private static final String TsSecuredConfiId = ((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredConfiId")).getString(); - - /** - * ITS-AID for Secure other profile - */ - private static final String TsItsAidOther = "141"; // GN-MGMT ((CharstringValue)TERFactory.getInstance().getTaParameter("TsItsAidOther")).getString(); - - /** - * Link-layer address of Component - */ - private byte[] linkLayerAddress = null; - - /** - * Registered GN Port - */ - private GnPort gnPort = null; - - /** - * Registered FSAP Port - */ - private FsapPort fsapPort = null; // FIXME Enhance this using Fsap.send() method - - /** - * Set to true is secured mode is set - */ - private boolean securedMode = false; - - /** - * The certificate identifier to used - */ - private String certificateId = "CERT_TS_A_AT"; - - /** - * The AT certificate - */ - private byte[] atCertificate = null; - - /** - * The certificate digest to used - */ - private byte[] atCertificateDigest = null; - - /** - * The private signing key to used - */ - private byte[] signingPrivateKey = null; - - /** - * The public signing key X to used - */ - private byte[] signingPublicKeyX = null; - - /** - * The public signing key Y to used - */ - private byte[] signingPublicKeyY = null; -// private byte[] toBeSignedDataDigest = null; -// private byte[] toBeSignedDataCertificate = null; - - /** - * Private constructor (Multiton pattern) - */ - private Management() { - - // For debug only: - byte[] mid = new byte[] {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00}; - byte[] lpv = new byte[] {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00}; - gnUpdateLocTable(mid, 0, lpv); - } - - /** - * Gets the Management instance associated to a component - * @param key Component name - * @return Management instance - */ - public static Management getInstance(String key) { - if (instances.get(key) == null){ - // Lazily create instance and try to add it to the map - Management instance = new Management(); - instances.putIfAbsent(key, instance); - } - return instances.get(key); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#startBeaconing(byte[]) - */ - @Override - public void startBeaconing(byte[] beaconHeader) { - this.beaconHeader = beaconHeader; - if(gnPort != null) { - gnPort.startBeaconning(); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#stopBeaconing() - */ - @Override - public void stopBeaconing() { - this.beaconHeader = null; - if(gnPort != null) { - gnPort.stopBeaconning(); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#startEnqueueingBeacons(byte[]) - */ - @Override - public void startEnqueueingBeacons(byte[] beaconHeader) { - this.enqueueBeacon = beaconHeader; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#stopEnqueueingBeacons() - */ - @Override - public void stopEnqueueingBeacons() { - this.enqueueBeacon = null; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#startMultipleBeaconing(byte[], int) - */ - @Override - public void startMultipleBeaconing(byte[] beaconHeader, int nbNeighbours) { - /* TODO: Multiple beacons */ - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#stopMultipleBeaconing() - */ - @Override - public void stopMultipleBeaconing() { - /* TODO: Multiple beacons */ - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementTA#getLongPositionVector(byte[]) - */ - @Override - public byte[] getLongPositionVector(byte[] targetGnAddress) { - byte[] mid = ByteHelper.extract(targetGnAddress, 2, 6); - TERFactory.getInstance().logDebug("getLongPositionVector: Looking for Loc Entry: " + ByteHelper.byteArrayToString(mid)); - long key = ByteHelper.byteArrayToLong(mid); - for(int i = 0; i < GET_LPV_TIMEOUT; ++i) { - if (locTable.containsKey(key)) { - ITuple entry = locTable.get(key); - return entry.getB(); - } - try { - Thread.sleep(GET_LPV_POLL_INTERVAL); - } catch (InterruptedException e) { - // Do nothing, we do not care - } - } - return null; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getGnBeacon() - */ - @Override - public byte[] getGnBeacon() { - return beaconHeader; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getGnBeaconInterval() - */ - @Override - public int getGnBeaconInterval() { - return GN_BEACON_INTERVAL; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getGnEnqueueBeacon() - */ - @Override - public byte[] getGnEnqueueBeacon() { - return enqueueBeacon; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#gnUpdateLocTable(byte[], long, byte[]) - */ - @Override - public void gnUpdateLocTable(byte[] mid, long timestamp, byte[] lpv) { - // Java does not provide unsigned int - timestamp &= 0xffffffffL; - long key = ByteHelper.byteArrayToLong(mid); - ITuple entry = locTable.get(key); - if(entry == null || entry.getA() < timestamp) { -// TERFactory.getInstance().logDebug("gnUpdateLocTable: Adding Loc Entry for: " + ByteHelper.byteArrayToString(mid)); - locTable.put(key, new Tuple(timestamp, lpv)); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getLinkLayerAddress() - */ - @Override - public byte[] getLinkLayerAddress() { - return linkLayerAddress; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getLinkLayerAddress() - */ - @Override - public void setLinkLayerAddress(byte[] linkLayerAddress) { - this.linkLayerAddress = linkLayerAddress; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getLatitude() - */ - @Override - public byte[] getLatitude() { - return ByteHelper.intToByteArray(latitude, 4); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#getLongitude() - */ - @Override - public byte[] getLongitude() { - return ByteHelper.intToByteArray(longitude, 4); - } - - /** - * Set to null in order to prevent Test Adapter from sending beacons - * Otherwise, it shall be set to a valid encoded beacon header to be send periodically by Test Adapter - * @see startEnqueueingBeacons - * @see stopEnqueueingBeacons - */ - private byte[] beaconHeader = null; - - /** - * Set to null if received Beacon messages have to be discarded by test adapter (= not enqueued) - * Otherwise, it shall be set to the to an encoded beacon header value acting as a filter for enqueueing received beacons - * @see startBeaconing - * @see stopBeaconing - */ - private byte[] enqueueBeacon = null; - - /** - * Table used to store neighbours (= SUT) position vectors - * @see gnUpdateLocTable - * @see getLongPositionVector - */ - private static Map> locTable = new HashMap>(); - - /* (non-Javadoc) - * @see org.etsi.its.adapter.IManagementLayers#registerBeaconThread(java.lang.Thread) - */ - @Override - public void registerGnPort(GnPort gnPort) { - this.gnPort = gnPort; - - // Ensure that management settings are reset - beaconHeader = null; - enqueueBeacon = null; - - locTable.clear(); - } - - @Override - public void setSecuredMode(final byte[] securityData) { - certificateId = ByteHelper.byteArrayWithLengthToString(ByteHelper.concat(ByteHelper.intToByteArray(securityData.length - 1, 4), securityData)); - if (securityData[securityData.length - 1] == 0x01) { - TsEnforceSecuredMode = "true"; - } else { - TsEnforceSecuredMode = "false"; - } - setupSecuredMode(); - } - - @Override - public void unsetSecuredMode() { - securedMode = false; - signingPrivateKey = null; - signingPublicKeyX = null; - signingPublicKeyY = null; - atCertificate = null; - atCertificateDigest = null; - } - - @Override - public boolean isEnforceSecuredModeSet() { - return TsEnforceSecuredMode.equals("true"); - } - - @Override - public boolean isSecuredModeSet() { - return securedMode; - } - - @Override - public BigInteger getSigningPrivateKey() { - return new BigInteger(signingPrivateKey); - } - - @Override - public byte[] getSigningPublicKeyX() { - return signingPublicKeyX; - } - - @Override - public byte[] getSigningPublicKeyY() { - return signingPublicKeyY; - } - - @Override - public byte[] getAtCertificate() { - return atCertificate; - } - - @Override - public byte[] getAtCertificateDigest() { - return atCertificateDigest; - } - - @Override - public int getItsAidOther() { - return new Integer(TsItsAidOther).intValue(); - } - - /** - * @desc This method setup secured mode according to ATS settings (AcSecPrimitive) and the Test adapter settings (TsEnforceSecuredMode flags) - * @see TsEnforceSecuredMode flags. - * @remark This method shall be called by the constructor only - */ - private void setupSecuredMode() { - TERFactory.getInstance().logDebug(">>> setupSecuredMode: " + certificateId); - - securedMode = true; - ICertificatesIO _certCache = CertificatesIOFactory.getInstance(); - if (!_certCache.loadCertificates(TsSecuredRootPath, TsSecuredConfiId)) { - securedMode = false; - } else { - ByteArrayOutputStream certificate = new ByteArrayOutputStream(); - _certCache.readCertificate(certificateId, certificate); - // Extract public keys - atCertificate = certificate.toByteArray(); - TERFactory.getInstance().logDebug("Management.setupSecuredMode: certificate=" + ByteHelper.byteArrayToString(atCertificate)); - // Compute AT certificate digest - byte[] atHash = CryptoLib.hashWithSha256(atCertificate); - atCertificateDigest = ByteHelper.extract(atHash, atHash.length - 8, 8); - TERFactory.getInstance().logDebug("Management.setupSecuredMode: atCertificateDigest=" + ByteHelper.byteArrayToString(atCertificateDigest)); - int offset = 16; // FIXME To be enhanced - // KeyX - signingPublicKeyX = new byte[32]; - System.arraycopy(atCertificate, offset, signingPublicKeyX, 0, 32); - offset += 32; - TERFactory.getInstance().logDebug("Management.setupSecuredMode: signingPublicKeyX=" + ByteHelper.byteArrayToString(signingPublicKeyX)); - // KeyY - signingPublicKeyY = new byte[32]; - System.arraycopy(atCertificate, offset, signingPublicKeyY, 0, 32); - TERFactory.getInstance().logDebug("Management.setupSecuredMode: signingPublicKeyY=" + ByteHelper.byteArrayToString(signingPublicKeyY)); - // Extract private keys - ByteArrayOutputStream signingPrivateKey = new ByteArrayOutputStream(); - _certCache.readSigningKey(certificateId, signingPrivateKey); - this.signingPrivateKey = signingPrivateKey.toByteArray().clone(); - TERFactory.getInstance().logDebug("Management.setupSecuredMode: signingPrivateKey=" + ByteHelper.byteArrayToString(this.signingPrivateKey)); - // TODO Add support of encryption - } - } - - /** - * Registers a FSAP port - * @param The FSAP port to register - */ - @Override - public void registerFsapPort(final FsapPort fsapPort) { - this.fsapPort = fsapPort; - } - - @Override - public void startSamTransmission(final byte[] sam) { - if(fsapPort != null) { - fsapPort.startSamTransmission(sam); - } - } - - @Override - public void stopSamTransmission() { - if(fsapPort != null) { - fsapPort.stopSamTransmission(); - } - } - -} // End of class Management diff --git a/javasrc/adapter/org/etsi/its/adapter/PcapMultiplexer.java b/javasrc/adapter/org/etsi/its/adapter/PcapMultiplexer.java deleted file mode 100644 index be065cc41d33a406f22b3ef1e7029647191348b0..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/PcapMultiplexer.java +++ /dev/null @@ -1,298 +0,0 @@ -/** - * Pcap capture multiplexor - * - * @author ETSI / STF424 - * @version $URL: $ - * $Id: $ - * Note Copy jnetpcap.jar in C:\WINDOWS\Sun\Java\lib\ext, location of jpcap library - */ -package org.etsi.its.adapter; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.Layer; -import org.etsi.ttcn.tci.CharstringValue; /* FIXME: import tci */ - -import org.jnetpcap.ByteBufferHandler; -import org.jnetpcap.Pcap; -import org.jnetpcap.PcapBpfProgram; -import org.jnetpcap.PcapHeader; -import org.jnetpcap.PcapIf; - -public class PcapMultiplexer implements Runnable { - - /** - * Unique instance of the factory - */ - private static final PcapMultiplexer instance = new PcapMultiplexer(); - - private static byte[] MAC_BROADCAST = new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; - - private StringBuilder errbuf = new StringBuilder(); // For any error msgs - - private String timestampOffset = ""; - - private PcapMultiplexer() { - - filter = ""; - offlineMode = ((CharstringValue)TERFactory.getInstance().getTaParameter("OfflineMode")).getString().toLowerCase().equals("true"); - if (!offlineMode) { - // Obtain the list of network interfaces - List alldevs = new ArrayList(); // Will be filled with NICs - - - int r = Pcap.findAllDevs(alldevs, errbuf); - if (r != Pcap.OK || alldevs.isEmpty()) { - TERFactory.getInstance().logError("Can't read list of devices, error is %s" + errbuf.toString()); - return; - } - - // Find the right interface - int ifaceIndex = 0; - String expectedIface = ((CharstringValue)TERFactory.getInstance().getTaParameter("LocalEthernetMAC")).getString().toLowerCase(); - for( ; ifaceIndex < alldevs.size(); ifaceIndex++) { - try { - if (expectedIface.equalsIgnoreCase(ByteHelper.byteArrayToString(alldevs.get(ifaceIndex).getHardwareAddress()))) { - // Interface found - break; - } - } catch (IOException e) { - // ignore - } - } - // Check result - if (ifaceIndex == alldevs.size()) { - throw new RuntimeException(String.format("PcapMultiplexer: Network interface %s not found", expectedIface)); - } - - device = alldevs.get(ifaceIndex); - //TERFactory.getInstance().logDebug("Listening: " + device.getName()); - } else { - file = ((CharstringValue)TERFactory.getInstance().getTaParameter("PcapFile")).getString().toLowerCase(); - if ((file == null) || file.isEmpty()) { - throw new RuntimeException(String.format("PcapMultiplexer: failed to open '%s'", file)); - } - timestampOffset = ((CharstringValue)TERFactory.getInstance().getTaParameter("OffsetTime")).getString().toLowerCase(); - } - } - - /** - * Gets the unique factory instance - * @return PcapMultiplexer instance - */ - public static PcapMultiplexer getInstance(){ - return instance; - } - - public synchronized void register(Layer client, byte[] macAddress, short frameType) { - //TERFactory.getInstance().logDebug(">>>PcapMultiplexer.registering: " + frameType); - - if(clientsToMacs.isEmpty()) { - if (!offlineMode) { // Open interface - int snaplen = 64 * 1024; // Capture all packets, no truncation - int flags = Pcap.MODE_PROMISCUOUS; // capture all packets - int timeout = 10; // 10 millis - pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf); - if (pcap == null) { // Check result - TERFactory.getInstance().logError("Error while opening device for capture: " + errbuf.toString()); - return; - } - captureThread = new Thread(this); - captureThread.start(); - filter = ""; - } else { // Open file - pcap = Pcap.openOffline(file, errbuf); - if (pcap == null) { // Check result - TERFactory.getInstance().logError("Error while opening device for capture: " + errbuf.toString()); - return; - } - captureThread = new Thread(this); - captureThread.start(); - filter = ""; - } - if (pcap == null) { // Check result - TERFactory.getInstance().logError("Error while opening device for capture: " + errbuf.toString()); - return; - } - captureThread = new Thread(this); - captureThread.start(); - if (!timestampOffset.isEmpty()) { - filter = "frame time_delta " + timestampOffset + " and "; - } - } - else { - //TERFactory.getInstance().logDebug("Another Client !"); - filter = filter + " and "; - } - - // Update Filter - String strMacAddress = String.format("%02x", macAddress[0]); - for(int i=1; i < macAddress.length; i++) { - strMacAddress += String.format(":%02x", macAddress[i]); - } - - filter = filter + "not ether src " + strMacAddress; - //TERFactory.getInstance().logDebug("New filter: " + filter); - - // Apply filter - PcapBpfProgram bpfFilter = new PcapBpfProgram(); - int optimize = 0; // 1 means true, 0 means false - int netmask = 0; - int r = pcap.compile(bpfFilter, filter, optimize, netmask); - if (r != Pcap.OK) { - //TERFactory.getInstance().logDebug("Filter error: " + pcap.getErr()); - } - pcap.setFilter(bpfFilter); - - // Register client - clientsToMacs.put(client.toString(), macAddress); - clientsToLayers.put(client.toString(), client); - clientsToFrameTypes.put(client.toString(), frameType); - } - - public synchronized void unregister(Layer client) { - if(clientsToMacs.containsKey(client.toString())) { - clientsToMacs.remove(client.toString()); - clientsToFrameTypes.remove(client.toString()); - clientsToLayers.remove(client.toString()); - - if(clientsToMacs.isEmpty()) { - pcap.breakloop(); - try { - captureThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - pcap.close(); - } - } - } - - /** - * Thread function for jpcap capture loop - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - - ByteBufferHandler handler = new ByteBufferHandler() { - - @Override - public void nextPacket(PcapHeader pcapHeader, ByteBuffer byteBuffer, Object user) { - if(byteBuffer.remaining() < 14) { - return; - } - - Map lowerInfo = new HashMap(); - - // Extract Dst info - byte[] dst = new byte[6]; - byteBuffer.get(dst, 0, dst.length); - lowerInfo.put(EthernetLayer.LINK_LAYER_DESTINATION, dst); - - // Skip Src - byteBuffer.position(byteBuffer.position() + 6); - - // Extract FrameType info - byte[] rawFrameType = new byte[2]; - byteBuffer.get(rawFrameType, 0, rawFrameType.length); - short frameType = ByteHelper.byteArrayToInt(rawFrameType).shortValue(); - - // Extract Data - byte[] data = new byte[byteBuffer.remaining()]; - byteBuffer.get(data, 0, byteBuffer.remaining()); - - // Dispatch - for (String mapKey : clientsToMacs.keySet()) { - if(frameType == clientsToFrameTypes.get(mapKey)) { - if(Arrays.equals(dst, MAC_BROADCAST) - || Arrays.equals(dst, clientsToMacs.get(mapKey))) { - - lowerInfo.put(Layer.RECEPTION_TIMESTAMP, pcapHeader.timestampInMicros()); - clientsToLayers.get(mapKey).receive(data, lowerInfo); - } - } - } - - } - }; - - if (offlineMode) { - try { - Thread.sleep(4000); // TOTO Use a parameter instead of an hardcoded value - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - pcap.loop(-1, handler, null); - } - - public byte[] sendPacket(Layer client, byte[] dest, byte[] payload) { - - if(clientsToMacs.containsKey(client.toString())) { - - byte[] packet = ByteHelper.concat( - dest, - clientsToMacs.get(client.toString()), - ByteHelper.intToByteArray(clientsToFrameTypes.get(client.toString()), 2), - payload); - - pcap.sendPacket(packet); - return packet; - } - return null; - } - - public void resetFilter(String pcapFilter) { - // Sanity check - if ((pcapFilter == null) || pcapFilter.isEmpty()) { - return; - } - - filter = pcapFilter; - TERFactory.getInstance().logDebug("resetFilter: New filter: " + filter); - - // Apply filter - PcapBpfProgram bpfFilter = new PcapBpfProgram(); - int optimize = 0; // 1 means true, 0 means false - int netmask = 0; - int r = pcap.compile(bpfFilter, filter, optimize, netmask); - if (r != Pcap.OK) { - TERFactory.getInstance().logError("Filter error: " + pcap.getErr()); - } else { - r = pcap. setFilter(bpfFilter); - if (r != Pcap.OK) { - TERFactory.getInstance().logError("Filter error: " + pcap.getErr()); - } - } - } - - /** - * Jpcap capture device - */ - private Pcap pcap; - - /** - * Jpcap capture thread instance. - */ - private Thread captureThread; - - PcapIf device = null; - boolean offlineMode = false; - String file = ""; - private String filter; - private Map clientsToMacs = new HashMap(); - private Map clientsToFrameTypes = new HashMap(); - private HashMap clientsToLayers = new HashMap(); - -} \ No newline at end of file diff --git a/javasrc/adapter/org/etsi/its/adapter/SecurityHelper.java b/javasrc/adapter/org/etsi/its/adapter/SecurityHelper.java deleted file mode 100644 index 2741311d21993c18016e4599b044dd31407217bf..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/SecurityHelper.java +++ /dev/null @@ -1,785 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.its.adapter; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -//import org.etsi.its.adapter.layers.ETSI; - - - -import de.fraunhofer.sit.c2x.CryptoLib; - -public class SecurityHelper { - - private static SecurityHelper Instance = new SecurityHelper(); - - public static SecurityHelper getInstance() { return Instance; } - - /** - * SSP value - * @see ETSI TS 103 097 - */ - public static final String SEC_SSP = "SSP"; - - /** - * ITS-AID value - * @see ETSI TS 103 097 - */ - public static final String SEC_ITS_AID = "ITS_AID"; - - /** - * Storage for received certificates - */ - private Map _neighborsCertificates = null; - - private SecurityHelper() { - _neighborsCertificates = new HashMap(); - } - - public byte[] size2tls(final int intx_value) { - byte[] result = null; - if (intx_value < 128) { // One byte length - result = new byte[] { (byte)intx_value }; - } else { - long lv = intx_value; - long bitLen = bitLength(lv); - long byteLen = byteLength(bitLen); - long flags = (long) ((byteLen | 1) << (byteLen * Byte.SIZE - bitLength(byteLen) - 1)); - long len = (long) (byteLen << (byteLen * Byte.SIZE - bitLength(byteLen) - 1)); - if ((flags & lv) != 0) { // We can encode the length on the MSB part - byteLen += 1; - len = (long) (byteLen << (byteLen * Byte.SIZE - bitLength(byteLen)) - 1); - } - result = ByteHelper.longToByteArray((long)(lv | len), (int) byteLen); - } - - return result; - } - - public long tls2size(final ByteArrayInputStream buf) { - // Sanity check - if (buf.available() == 0) { - return 0; - } - - // Read the first byte - byte msb = (byte) buf.read(); - if ((msb & 0x80) == 0x00) { // Integer < 128 - return msb; - } else { - // Decode the length. The encoding of the length shall use at most 7 bits set to 1 (see Draft ETSI TS 103 097 V1.1.14 Clause 4.1 Presentation Language Table 1/8) - byte bit; - byte byteLen = 1; - do { - bit = (byte) ((byte) (msb << byteLen++) & 0x80); - } while (bit != 0x00); - // Set the IntX length - byte[] data = new byte[byteLen - 1]; - buf.read(data, 0, byteLen - 1); - byte[] length = ByteHelper.concat(new byte[] { msb }, data); - length[0] &= (byte)(Math.pow(2.0, 8 - byteLen + 1) - 1); - long lv = ByteHelper.byteArrayToLong(length); - return lv; - } - } - - public long bitLength(final long value) { - return (long) Math.ceil(Math.log(value) / Math.log(2)); - } - - public long byteLength(final long value) { - double d = value; // Convert int to double - return (long) Math.ceil(d / Byte.SIZE); - } - - public byte[] checkSecuredProfileAndExtractPayload(final byte[] p_message, final int p_offset, final boolean p_enforceSecurityCheck, final int p_itsAidOther, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> SecurityHelper.checkSecuredProfileAndExtractPayload: " + ByteHelper.byteArrayToString(p_message)); - - ByteArrayInputStream decvalue = new ByteArrayInputStream(p_message, p_offset, p_message.length - p_offset); - - // Check version - if (decvalue.read() != 2) { - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkSecuredProfileAndExtractPayload: Drop packet - Wrong version number"); - return null; - } - } - // Extract header fields length and header fields - long headerFieldsLength = tls2size(decvalue); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: headerFieldsLength:" + headerFieldsLength); - byte[] headerFields = new byte[(int) headerFieldsLength]; - decvalue.read(headerFields, 0, (int) headerFieldsLength); - ByteArrayOutputStream certificateKeys = new ByteArrayOutputStream(); - if (!checkHeaderfields(headerFields, certificateKeys, p_enforceSecurityCheck, p_itsAidOther, lowerInfo)) { - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkSecuredProfileAndExtractPayload: Drop packet - Wrong Headerfields"); - return null; - } - } - byte[] aaSigningPublicKeyX = null, aaSigningPublicKeyY = null; - if (p_enforceSecurityCheck) { - byte[] keys = certificateKeys.toByteArray(); - if ((keys[0] == 0x02) || (keys[0] == 0x03)) { // Key length = 32 bytes - aaSigningPublicKeyX = ByteHelper.extract(keys, 1, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - } else { // Key length = 64 bytes - aaSigningPublicKeyX = ByteHelper.extract(keys, 1, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - aaSigningPublicKeyY = ByteHelper.extract(keys, 33, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - } - } - // FIXME Add encryption support -// if (p_enforceSecurityCheck) { -// } - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: headerFields:" + ByteHelper.byteArrayToString(headerFields)); - // Extract payload, decvalue is updated with the payload - if (decvalue.read() != 1) { - //TERFactory.getInstance().logError("SecurityHelper.checkSecuredProfileAndExtractPayload: Drop packet - Wrong Payload type"); - if (p_enforceSecurityCheck) { - // Drop it - return null; - } - } - long payloadLength = tls2size(decvalue); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: payloadLength:" + payloadLength); - byte[] payload = new byte[(int) payloadLength]; - decvalue.read(payload, 0, (int) payloadLength); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: payload:" + ByteHelper.byteArrayToString(payload)); - if (p_enforceSecurityCheck) { // Extract Secure Trailer - long secureTrailerLength = tls2size(decvalue); - byte[] secureTrailer = new byte[(int) secureTrailerLength]; - decvalue.read(secureTrailer, 0, secureTrailer.length); - ByteArrayOutputStream signature = new ByteArrayOutputStream(); - if (!extractMessageSignature(secureTrailer, signature)) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkSecuredProfileAndExtractPayload: Drop packet - Wrong Signatures"); - return null; - } - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: signature:" + ByteHelper.byteArrayToString(signature.toByteArray())); - // Build signed data - byte[] toBeVerifiedData = ByteHelper.extract( - p_message, - p_offset, - p_message.length - (int)(p_offset + secureTrailerLength - 1 /* Exclude signature structure but keep signature type and signature length */) - ); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload:" + ByteHelper.byteArrayToString(toBeVerifiedData)); - boolean result; - try { - if (aaSigningPublicKeyY == null) { - // FIXME FSCOM: Check how t verify compressed signature - return payload; - } - result = CryptoLib.verifyWithEcdsaNistp256WithSha256( - toBeVerifiedData, - signature.toByteArray(), - aaSigningPublicKeyX, - aaSigningPublicKeyY - ); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: Verify signature: " + new Boolean(result)); - if (!result) { - // Drop packet - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: toBeVerifiedData :" + ByteHelper.byteArrayToString(toBeVerifiedData)); - // Calculate Digest digest from the buffer toBeVerifiedData - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: Hash :" + ByteHelper.byteArrayToString(CryptoLib.hashWithSha256(toBeVerifiedData))); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: signature :" + ByteHelper.byteArrayToString(signature.toByteArray())); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - //TERFactory.getInstance().logDebug("SecurityHelper.checkSecuredProfileAndExtractPayload: aaSigningPublicKeyY:" + ByteHelper.byteArrayToString(aaSigningPublicKeyY)); - //TERFactory.getInstance().logError("SecurityHelper.checkSecuredProfileAndExtractPayload: Drop packet - Invalid signature"); - return null; - } - - return payload; - } catch (Exception e) { - e.printStackTrace(); - } - - // Drop packet - //TERFactory.getInstance().logError("<<< SecurityHelper.checkSecuredProfileAndExtractPayload: dropped"); - return null; - } - - return payload; - } - - public boolean checkHeaderfields(final byte[] p_headerfields, final ByteArrayOutputStream p_keys, final boolean p_enforceSecurityCheck, final int p_itsAidOther, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> SecurityHelper.checkHeaderfields: " + ByteHelper.byteArrayToString(p_headerfields)); - - // Sanity check - if (p_headerfields.length == 0) { - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Invalid header fields"); - return false; - } - // Extract digest or certificate - int signerInfoTypeIndex = 0; - if ( - ((p_headerfields[signerInfoTypeIndex] & 0x80) != 0x80) || // SignerInfo Type: certificate digest with ecdsap256 (1) - ( - (p_headerfields[signerInfoTypeIndex + 1] != 0x01) && // SignerInfo Type: certificate digest with ecdsap256 (1) - (p_headerfields[signerInfoTypeIndex + 1] != 0x02) && // SignerInfo Type: certificate (2) - (p_headerfields[signerInfoTypeIndex + 1] != 0x03) // SignerInfo Type: certificate chain (3) - ) - ) { - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Certificate"); - if (p_enforceSecurityCheck) { - // Drop it - return false; - } - } - signerInfoTypeIndex += 1; - if (p_headerfields[signerInfoTypeIndex] == 0x02) { // SignerInfo Type: Certificate (2) - signerInfoTypeIndex += 1; - // Extract certificate because of it is an Other message profile - byte[] certificate = decodeCertificate(p_headerfields, signerInfoTypeIndex, p_keys, p_enforceSecurityCheck, lowerInfo); - if (certificate == null) { - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Certificate not decoded"); - if (p_enforceSecurityCheck) { - // Drop it - return false; - } - } - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Certificate=" + ByteHelper.byteArrayToString(certificate)); - // Add it in our map - Long lKey = ByteHelper.byteArrayToLong(calculateDigestFromCertificate(certificate)); - if (!_neighborsCertificates.containsKey(lKey)) { - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Add keys for " + ByteHelper.byteArrayToString(calculateDigestFromCertificate(certificate)) + " / " + lKey); - _neighborsCertificates.put(lKey, p_keys); - } - signerInfoTypeIndex += certificate.length; - } else if (p_headerfields[signerInfoTypeIndex] == 0x01) { // SignerInfo Type: certificate digest with SHA256 (1) - signerInfoTypeIndex += 1; - byte[] hashedid8 = ByteHelper.extract(p_headerfields, signerInfoTypeIndex, Long.SIZE / Byte.SIZE); - signerInfoTypeIndex += (Long.SIZE / Byte.SIZE); - Long lKey = ByteHelper.byteArrayToLong(hashedid8); - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Certificate digest with SHA256=" + lKey + " / " + ByteHelper.byteArrayToString(hashedid8)); - if (!_neighborsCertificates.containsKey(lKey) || (_neighborsCertificates.get(lKey) == null)) { //FIXME as long as the cert chain is not complete, it should not be seen as error -> raise CR - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Unknown HahedId8"); - return false; - } - } - try { - p_keys.write(_neighborsCertificates.get(lKey).toByteArray()); - } catch (Exception e) { - // Drop it - //e.printStackTrace(); - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: key " + lKey + "_neighbors certificates table"); - return false; - } - } - } else { // TODO Add certchain support - signerInfoTypeIndex += 1; - ByteArrayInputStream ba = new ByteArrayInputStream(ByteHelper.extract(p_headerfields, signerInfoTypeIndex, p_headerfields.length - signerInfoTypeIndex)); - int certChainLength = (int) this.tls2size(ba); - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Certchain length = " + certChainLength); - signerInfoTypeIndex += this.size2tls(certChainLength).length; - ByteArrayOutputStream keys; - do { - // Extract certificate because of it is an Other message profile - keys = new ByteArrayOutputStream(); - byte[] certificate = decodeCertificate(p_headerfields, signerInfoTypeIndex, keys, p_enforceSecurityCheck, lowerInfo); - if (certificate == null) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Failed to decode chain of certificate"); - return false; - } - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Certificate=" + ByteHelper.byteArrayToString(certificate)); - // Add it in our map - Long lKey = ByteHelper.byteArrayToLong(calculateDigestFromCertificate(certificate)); - if (!_neighborsCertificates.containsKey(lKey)) { - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Add keys for " + ByteHelper.byteArrayToString(calculateDigestFromCertificate(certificate)) + " / " + lKey); - _neighborsCertificates.put(lKey, p_keys); - } - certChainLength -= certificate.length; - signerInfoTypeIndex += certificate.length; - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: Extracted certificate = " + ByteHelper.byteArrayToString(certificate)); - } while (certChainLength > 0); - } - // Check generation time - if (p_headerfields[signerInfoTypeIndex++] != 0x00) { // Header Field: Generation Time (0) - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - GenerationTime not found"); - return false; - } - } - long generationTime = ByteHelper.byteArrayToLong(ByteHelper.extract(p_headerfields, signerInfoTypeIndex, Long.SIZE / Byte.SIZE)); - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: generationTime=" + generationTime); - if (Math.abs(System.currentTimeMillis() - generationTime) < 1000) { - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - GenerationTime out of range"); - return false; - } - } - signerInfoTypeIndex += (Long.SIZE / Byte.SIZE); - - if (signerInfoTypeIndex < p_headerfields.length) { - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: dump #1=" + ByteHelper.byteArrayToString(ByteHelper.extract(p_headerfields, signerInfoTypeIndex, p_headerfields.length - signerInfoTypeIndex))); - if (p_headerfields[signerInfoTypeIndex] == 0x03) { // Header Field: Generation Location (3) - signerInfoTypeIndex += 1; - byte[] lat = ByteHelper.extract(p_headerfields, signerInfoTypeIndex, 4); - signerInfoTypeIndex += 4; - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: latitude=" + ByteHelper.byteArrayToString(lat)); - byte[] lon = ByteHelper.extract(p_headerfields, signerInfoTypeIndex, 4); - signerInfoTypeIndex += 4; - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: longitude=" + ByteHelper.byteArrayToString(lon)); - byte[] ele = ByteHelper.extract(p_headerfields, signerInfoTypeIndex, 2); - signerInfoTypeIndex += 2; - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: elevation=" + ByteHelper.byteArrayToString(ele)); - } - } - if (signerInfoTypeIndex < p_headerfields.length) { - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: dump #2=" + ByteHelper.byteArrayToString(ByteHelper.extract(p_headerfields, signerInfoTypeIndex, p_headerfields.length - signerInfoTypeIndex))); - if (p_headerfields[signerInfoTypeIndex] == 0x05) { // Header Field: Its AID (5) - signerInfoTypeIndex += 1; - // Check ItsAid - if ((p_headerfields[signerInfoTypeIndex] & 0x80) == 0x00) { // Short integer - if ( - (p_headerfields[signerInfoTypeIndex] != 0x24) && // CAM - (p_headerfields[signerInfoTypeIndex] != 0x25) && // DENM - (p_headerfields[signerInfoTypeIndex] != p_itsAidOther) - ) { - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Unknown ItsAid value"); - return false; - } - } - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: ItsAid=" + p_headerfields[signerInfoTypeIndex]); - lowerInfo.put(SecurityHelper.SEC_ITS_AID, ByteHelper.intToByteArray(p_headerfields[signerInfoTypeIndex], Integer.SIZE / Byte.SIZE)); - signerInfoTypeIndex += 1; - } else { // FIXME To be refined - signerInfoTypeIndex += 1; - if ( - (p_headerfields[signerInfoTypeIndex] != 0x89) && // SPATEM - (p_headerfields[signerInfoTypeIndex] != 0x8a) && // MAPEM - (p_headerfields[signerInfoTypeIndex] != 0x8b) && // IVIM - (p_headerfields[signerInfoTypeIndex] != 0x8d) && // EVCSN TODO Use the correct value - (p_headerfields[signerInfoTypeIndex] != 0x8c) // SREM/SSEM - ) { - if (p_enforceSecurityCheck) { - // Drop it - //TERFactory.getInstance().logError("SecurityHelper.checkHeaderfields: Drop packet - Unknown ItsAid value"); - return false; - } - } - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: ItsAid=" + p_headerfields[signerInfoTypeIndex]); - lowerInfo.put(SecurityHelper.SEC_ITS_AID, ByteHelper.intToByteArray(p_headerfields[signerInfoTypeIndex], Integer.SIZE / Byte.SIZE)); - signerInfoTypeIndex += 1; - } - } - } - if (signerInfoTypeIndex < p_headerfields.length) { - // TODO check other fields - //TERFactory.getInstance().logDebug("SecurityHelper.checkHeaderfields: dump #3=" + ByteHelper.byteArrayToString(ByteHelper.extract(p_headerfields, signerInfoTypeIndex, p_headerfields.length - signerInfoTypeIndex))); - } - - return true; - } - - public byte[] decodeCertificate(final byte[] p_headerfields, final int p_offset, final ByteArrayOutputStream p_keys, final boolean p_enforceSecurityCheck, Map p_lowerInfo) { - //TERFactory.getInstance().logDebug(">>> SecurityHelper.decodeCertificate: " + ByteHelper.byteArrayToString(ByteHelper.extract(p_headerfields, p_offset, p_headerfields.length - p_offset))); - - ByteArrayInputStream headerfields = new ByteArrayInputStream(p_headerfields, p_offset, p_headerfields.length - p_offset); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: headerfields length=" + headerfields.available()); - ByteArrayOutputStream cert = new ByteArrayOutputStream(); // FIXME To be removed - try { - // Version - cert.write((byte)headerfields.read()); - if (cert.toByteArray()[0] != 0x02) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Wrong version number"); - if (p_enforceSecurityCheck) { - // Drop it - return null; - } // else continue - } - // SignerInfo type - byte signerInfoType = (byte)headerfields.read(); - cert.write(signerInfoType); - switch (signerInfoType) { - case 0x01: - byte[] digest = new byte[8]; - headerfields.read(digest, 0, digest.length); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: hashedid8=" + ByteHelper.byteArrayToString(digest)); - cert.write(digest); - break; - // FIXME To be continued - } // End of 'switch' statement - // SubjectInfo type - byte subjectInfoType = (byte)headerfields.read(); - if ( - (subjectInfoType != 0x01) && // Subject Info: authorization ticket (1) - (subjectInfoType != 0x02) // Subject Info: authorization authority (2) - ) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Subject Info: authorization authority/ticket expected - " + ByteHelper.byteArrayToString(cert.toByteArray())); - return null; - } - cert.write(subjectInfoType); - long length = tls2size(headerfields); - if (length != 0) { - cert.write(size2tls((int) length)); - byte[] subjectInfo = new byte[(int) length]; - headerfields.read(subjectInfo, 0, subjectInfo.length); - cert.write(subjectInfo); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: subjectInfo: " + ByteHelper.byteArrayToString(subjectInfo)); - } else { - cert.write(0x00); - } - // Subject Attributes length - length = tls2size(headerfields); - cert.write(size2tls((int) length)); - // Subject Attributes - byte[] b = new byte[(int) length]; - headerfields.read(b, 0, b.length); - cert.write(b); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Subject Attributes length=" + length + " / " + headerfields.available()); - ByteArrayInputStream subjectAttributes = new ByteArrayInputStream(b); - if (subjectAttributes.read() == 0x00) { // Subject Attribute: verification key (0) - Mandatory - if (subjectAttributes.read() == 0x00) { // Public Key Alg: ecdsa nistp256 with sha256 (0) - byte v = (byte) subjectAttributes.read(); - p_keys.write(v); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: ECC Point Type: =" + v); - if (v == 0x02) { // ECC Point Type: compressed lsb y-0(2) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Verification lsb y-1 key=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } else if (v == 0x03) { // ECC Point Type: compressed lsb y-1(3) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Verification lsb y-1 key=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } else if (v == 0x04) { // ECC Point Type: uncompressed (4) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Verification key1=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Verification key2=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - - // Read the next header - byte v = (byte) subjectAttributes.read(); - if (v == 0x01) { // // Subject Attribute: encryption key (1) - if (subjectAttributes.read() == 0x01) { // Public Key Alg: ecdsa nistp256 (1) - if (subjectAttributes.read() == 0x00) { // Symmetric Algorithm: aes 128 ccm (0) - v = (byte) subjectAttributes.read(); - p_keys.write(v); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: ECC Point Type: =" + v); - if (v == 0x02) { // ECC Point Type: compressed lsb y-0(2) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Encryption lsb y-0 key=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } else if (v == 0x03) { // ECC Point Type: compressed lsb y-1(3) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Encryption lsb y-1 key=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } else if (v == 0x04) { // ECC Point Type: uncompressed (4) - byte[] key = new byte[32]; - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Encryption key1=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - subjectAttributes.read(key, 0, 32); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Encryption key2=" + ByteHelper.byteArrayToString(key)); - p_keys.write(key); - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - - // Read the next header - v = (byte) subjectAttributes.read(); - } // FIXME To be continued - - // Assurance level - if (v != 0x02) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Assurance level expected - " + ByteHelper.byteArrayToString(cert.toByteArray())); - return null; - } - v = (byte) subjectAttributes.read(); // Skip assurance level value - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: assurance level value=" + v); - if (subjectInfoType == 0x01) { // Authorization Ticket - if (subjectAttributes.read() != 0x21) { // Subject Attribute: its aid ssp list (33) - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Its aid ssp list expected - " + ByteHelper.byteArrayToString(cert.toByteArray())); - return null; - } - length = tls2size(subjectAttributes); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Its aid ssp length=" + length); - byte[] its_aid_ssp_list = new byte[(int) length]; - subjectAttributes.read(its_aid_ssp_list, 0, (int) length); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: its_aid_list=" + ByteHelper.byteArrayToString(its_aid_ssp_list)); - byte[] padding = new byte[32 - (int) length]; - ByteHelper.fill(padding, 32 - (int) length, (byte)0x00); - p_lowerInfo.put( - SecurityHelper.SEC_SSP, - ByteHelper.concat( - padding, - its_aid_ssp_list - )); - // TODO Process ATS AID list - } else if (subjectInfoType == 0x02) { // Authorization Authority - if (subjectAttributes.read() != 0x20) { // Subject Attribute: its aid ssp (32) - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Its aid list expected - " + ByteHelper.byteArrayToString(cert.toByteArray())); - return null; - } - length = tls2size(subjectAttributes); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: its_aid_list length=" + length); - byte[] its_aid_list = new byte[(int) length]; - subjectAttributes.read(its_aid_list, 0, (int) length); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: its_aid_list=" + ByteHelper.byteArrayToString(its_aid_list)); - // TODO Process ATS AID list - } else { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Unknown subjectInfoType - " + subjectInfoType); - return null; - } - - // Validity restrictions - length = tls2size(headerfields); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Length=" + length + " / " + headerfields.available()); - cert.write(size2tls((int)length)); - v = (byte)headerfields.read(); - if (v == 0x00) { // Validity Restriction: time end (0) - cert.write(v); - byte[] time = new byte[4]; - headerfields.read(time, 0, 4); - cert.write(time); - int endTime = ByteHelper.byteArrayToInt(time); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: endTime=" + endTime); - // Check times - long currentTime = (System.currentTimeMillis() - 1072915200000L) / 1000L; - if (currentTime > endTime) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Validity Restriction: time end not matched"); - return null; - } - v = (byte)headerfields.read(); - } - if (v == 0x01) { // Validity Restriction: time start and end (1) - cert.write(v); - byte[] time = new byte[4]; - headerfields.read(time, 0, 4); - cert.write(time); - int startTime = ByteHelper.byteArrayToInt(time); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: startTime=" + startTime); - headerfields.read(time, 0, 4); - cert.write(time); - int endTime = ByteHelper.byteArrayToInt(time); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: endTime=" + endTime); - // Check times - long currentTime = (System.currentTimeMillis() - 1072915200000L) / 1000L; - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: currentTime=" + currentTime); - if ((currentTime < startTime) || (currentTime > endTime)) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Validity Restriction: time start and end not matched"); - return null; - } - v = (byte)headerfields.read(); - } - if (v == 0x02) { // Validity Restriction: time start and duration (2) - cert.write(v); - byte[] time = new byte[4]; - headerfields.read(time, 0, 4); - cert.write(time); - int startTime = ByteHelper.byteArrayToInt(time); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: startTime=" + startTime); - byte[] dur = new byte[2]; - headerfields.read(dur, 0, 2); - cert.write(dur); - short duration = ByteHelper.byteArrayToShort(dur); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: duration=" + duration); - int unit = (duration & 0xe0000) >>> 13; - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: unit=" + unit); - long value = (duration & 0x1fff); - switch (unit) { - case 0: - // Nothing to do - break; - case 1: - value *= 60; - break; - case 2: - value *= 3600; - break; - default: - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Validity Restriction: time start and duration not processed"); - value = Long.MAX_VALUE; - } // End of 'switch' statement - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Validity Restriction: value=" + value); - // Check times - long currentTime = (System.currentTimeMillis() - 1072915200000L) / 1000L; - if ((currentTime < startTime) || (currentTime > (startTime + value))) { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Validity Restriction: time start and duration not matched"); - return null; - } - v = (byte)headerfields.read(); - } - if (v == 0x03) { // region (3) - cert.write(v); - // Region type - v = (byte)headerfields.read(); - cert.write(v); - if (v == 0x00) { // none (0) - // Nothing to do - } else if (v == 0x01) { // circle (1) - byte[] lat = new byte[4]; - headerfields.read(lat, 0, lat.length); - cert.write(lat); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Circle lat=" + ByteHelper.byteArrayToString(lat)); - byte[] lon = new byte[4]; - headerfields.read(lon, 0, lon.length); - cert.write(lon); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Circle lon=" + ByteHelper.byteArrayToString(lon)); - byte[] rad = new byte[2]; - headerfields.read(rad, 0, rad.length); - cert.write(rad); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Circle rad=" + ByteHelper.byteArrayToInt(rad)); - } else if (v == 0x02) { // rectangle (2) - int rlength = (int) tls2size(headerfields); - cert.write(size2tls(rlength)); - while (rlength > 0) { - byte[] ulat = new byte[4]; - headerfields.read(ulat, 0, ulat.length); - cert.write(ulat); - byte[] ulon = new byte[4]; - headerfields.read(ulon, 0, ulon.length); - cert.write(ulon); - byte[] llat = new byte[4]; - headerfields.read(llat, 0, llat.length); - cert.write(llat); - byte[] llon = new byte[4]; - headerfields.read(llon, 0, llon.length); - cert.write(llon); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Rectangle ulat=" + ByteHelper.byteArrayToString(ulat)); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Rectangle ulon=" + ByteHelper.byteArrayToString(ulon)); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Rectangle llat=" + ByteHelper.byteArrayToString(llat)); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Rectangle llon=" + ByteHelper.byteArrayToString(llon)); - rlength -= 4 * 4; - } - } else if (v == 0x03) { // polygon (3) - int plength = (int) tls2size(headerfields); - cert.write(size2tls((int) plength)); - byte[] polygonalRegion = new byte[plength]; - while (plength > 0) { - byte[] lat = new byte[4]; - headerfields.read(lat, 0, lat.length); - cert.write(lat); - byte[] lon = new byte[4]; - headerfields.read(lon, 0, lon.length); - cert.write(lon); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: poly point lat=" + ByteHelper.byteArrayToString(lat)); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: poly point lon=" + ByteHelper.byteArrayToString(lon)); - plength -= 2 * 4; - } - headerfields.read(polygonalRegion, 0, polygonalRegion.length); - cert.write(polygonalRegion); - // TODO Process Validity Restriction - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: polygonal=" + ByteHelper.byteArrayToString(polygonalRegion)); - - } else if (v == 0x04) { // id (4) - v = (byte)headerfields.read(); - cert.write(v); - byte[] ri = new byte[2]; - headerfields.read(ri, 0, ri.length); - cert.write(ri); - int lr = (int) tls2size(headerfields); - cert.write(size2tls((int) lr)); - // TODO Process Validity Restriction - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Region t=" + v); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Region ri=" + ByteHelper.byteArrayToString(ri)); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Region lr=" + lr); - } else { - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Unexpected geographical region"); - return null; - } - } - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Before signature: " + ByteHelper.byteArrayToString(cert.toByteArray())); - // Signature - byte publicKeyAlg = (byte)headerfields.read(); - cert.write(publicKeyAlg); - switch (publicKeyAlg) { - case 0x00: // ecdsa nistp256 with sha256 - byte eccPointType = (byte)headerfields.read(); - cert.write(eccPointType); - switch (eccPointType) { - case 0x00: // ECC Point Type: x-coordinate only - byte[] key = new byte[64]; - headerfields.read(key, 0, key.length); - cert.write(key); - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Signature=" + ByteHelper.byteArrayToString(key)); - break; - } // End of 'switch' statement - break; - } // End of 'switch' statement - // TODO Check certificate signature - - //TERFactory.getInstance().logDebug("SecurityHelper.decodeCertificate: Processed cert=" + ByteHelper.byteArrayToString(cert.toByteArray())); - return cert.toByteArray(); - } catch (IOException e) { - e.printStackTrace(); - } - - //TERFactory.getInstance().logError("SecurityHelper.decodeCertificate: Unsupported certificate - " + ByteHelper.byteArrayToString(cert.toByteArray())); - return null; - } - - public boolean extractMessageSignature(final byte[] p_secureTrailer, final ByteArrayOutputStream p_signature) { - //TERFactory.getInstance().logDebug(">>> SecurityHelper.extractMessageSignature: " + ByteHelper.byteArrayToString(p_secureTrailer)); - - // Sanity check - if (p_secureTrailer.length == 0) { - return false; - } - - // Extract digest or certificate - int secureTrailerIndex = 0; - if (p_secureTrailer[secureTrailerIndex++] == 0x01) { // Trailer Type: signature (1) - if (p_secureTrailer[secureTrailerIndex++] == 0x00) { // Public Key Alg: ecdsa nistp256 with sha256 (0) - byte v = p_secureTrailer[secureTrailerIndex++]; - if ((v == 0x00) || (v == 0x02)) { // ECC Point Type: compressed lsb y-0 (2) - if (p_secureTrailer.length == (3 + 2 * 32)) { - // Build the signature vector - try { - p_signature.write(new byte[] { (byte)0x00, (byte)0x00 }); - p_signature.write(ByteHelper.extract(p_secureTrailer, 3, 64)); - - //TERFactory.getInstance().logDebug("<<< SecurityHelper.extractMessageSignature: true"); - return true; - } catch (IOException e) { - e.printStackTrace(); - } - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - - // Else, drop it - //TERFactory.getInstance().logError("SecurityHelper.extractMessageSignature: Drop packet - Wrong signature"); - return false; - } - - public byte[] calculateDigestFromCertificate(final byte[] p_toBeHashedData) { - //TERFactory.getInstance().logDebug("SecurityHelper.calculateDigestFromCertificate: " + ByteHelper.byteArrayToString(p_toBeHashedData)); - byte[] hash = CryptoLib.hashWithSha256(p_toBeHashedData); - //TERFactory.getInstance().logDebug("SecurityHelper.calculateDigestFromCertificate: " + ByteHelper.byteArrayToString(hash)); - return ByteHelper.extract(hash, hash.length - 8, 8); - } - -} // End of class SecurityHelper diff --git a/javasrc/adapter/org/etsi/its/adapter/TestAdapter.java b/javasrc/adapter/org/etsi/its/adapter/TestAdapter.java deleted file mode 100644 index cdc39f2f7b76145258c0136c7bad0ce883d6270c..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/TestAdapter.java +++ /dev/null @@ -1,344 +0,0 @@ -/** - * Main Test Adapter class. Implements TRI API - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * @see "http://t-ort.etsi.org/view_all_bug_page.php?page_number=1" - */ -package org.etsi.its.adapter; - -import java.util.Observable; -import java.util.Observer; - -import org.etsi.adapter.ITERequired; -import org.etsi.adapter.TERFactory; -import org.etsi.its.adapter.ports.AdapterControlPort; -import org.etsi.its.adapter.ports.ConfigTesterPort; -import org.etsi.its.adapter.ports.IPort; -import org.etsi.its.adapter.ports.PortEvent; -import org.etsi.its.adapter.ports.ProtocolPortFactory; -import org.etsi.its.adapter.ports.UpperTesterPort; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tri.TriAddress; -import org.etsi.ttcn.tri.TriAddressList; -import org.etsi.ttcn.tri.TriCommunicationSA; -import org.etsi.ttcn.tri.TriComponentId; -import org.etsi.ttcn.tri.TriException; -import org.etsi.ttcn.tri.TriMessage; -import org.etsi.ttcn.tri.TriParameter; -import org.etsi.ttcn.tri.TriParameterList; -import org.etsi.ttcn.tri.TriPortId; -import org.etsi.ttcn.tri.TriPortIdList; -import org.etsi.ttcn.tri.TriSignatureId; -import org.etsi.ttcn.tri.TriStatus; -import org.etsi.ttcn.tri.TriTestCaseId; - -/** - * Main Test Adapter class. Implements TRI API in a tool independent manner - */ -@SuppressWarnings({ "serial", "deprecation" }) -public class TestAdapter implements TriCommunicationSA, Observer { - - /** - * Mapping (component-) support for layered port - */ - protected ComponentMgr compPortMgr; - - /** - * Provides all TE related interfaces - */ - protected ITERequired required; - - /** - * Constructor - */ - public TestAdapter() { - super(); - - compPortMgr = new ComponentMgr(this); - required = TERFactory.getInstance(); - } - - /** - * This method will force a Test adapter reset - * @see org.etsi.ttcn.tri.TriCommunicationSA#triEndTestCase() - */ - @Override - public TriStatus triEndTestCase() { - triSAReset(); - return required.getTriStatus(TriStatus.TRI_OK); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triExecuteTestcase(org.etsi.ttcn.tri.TriTestCaseId, org.etsi.ttcn.tri.TriPortIdList) - */ - public TriStatus triExecuteTestcase(final TriTestCaseId tcId, final TriPortIdList portList) { - return required.getTriStatus(TriStatus.TRI_OK); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triMap(org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriPortId) - */ - @Override - public TriStatus triMap(final TriPortId compPortId, final TriPortId tsiPortId) { - - IPort port; - String portName = tsiPortId.getPortName(); - String ComponentId = compPortId.getComponent().getComponentId(); - - if (tsiPortId.getPortName().equals("acPort")) { - port = new AdapterControlPort(portName, ComponentId); - } else if (tsiPortId.getPortName().toLowerCase().endsWith("utport")) { - port = new UpperTesterPort(portName, ComponentId); - } else if (tsiPortId.getPortName().toLowerCase().endsWith("cfport")) { - port = new ConfigTesterPort(portName, ComponentId); - } else { - String componentName = compPortId.getComponent().getComponentName(); - - // Dirty hack due to LinkLayer_MTC removal. - if(componentName.equalsIgnoreCase("MTC")) { - componentName = "NodeB"; - } - - port = ProtocolPortFactory.getInstance().createPort( - tsiPortId.getPortName(), - ComponentId, - ((CharstringValue)required.getTaParameter(portName)).getString(), - ((CharstringValue)required.getTaParameter("LinkLayer_" + componentName)).getString()); - } - - compPortMgr.addComponent(compPortId.getComponent()); - compPortMgr.addPort(ComponentId, tsiPortId, port); - - return required.getTriStatus(TriStatus.TRI_OK); - } - - /** - * This method will force port unmapping - * @see org.etsi.ttcn.tri.TriCommunicationSA#triSAReset() - */ - @Override - public TriStatus triSAReset() { - - // Force port unmapping - compPortMgr.removeAllPorts(); - - // Load certificates - org.etsi.certificates.CertificatesIOFactory.getInstance().loadCertificates(((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredRootPath")).getString(), ((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredConfiId")).getString()); - - return required.getTriStatus(TriStatus.TRI_OK); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triSend(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddress, org.etsi.ttcn.tri.TriMessage) - */ - @Override - public TriStatus triSend(TriComponentId componentId, TriPortId tsiPortId, TriAddress address, TriMessage message) { - - IPort port = compPortMgr.getPort(componentId.getComponentId(), tsiPortId.getPortName()); - if (port == null) { - return required.getTriStatus(TriStatus.TRI_ERROR, "Unknown port"); - } - - port.send(message.getEncodedMessage()); - return required.getTriStatus(TriStatus.TRI_OK); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triSendBC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriMessage) - */ - @Override - public TriStatus triSendBC(TriComponentId componentId, TriPortId portId, TriMessage message) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triSendBC not implemented"); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triSendMC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddressList, org.etsi.ttcn.tri.TriMessage) - */ - @Override - public TriStatus triSendMC(TriComponentId componentId, TriPortId portId, TriAddressList addressList, TriMessage message) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triSendMC not implemented"); - } - - /* (non-Javadoc) - * @see org.etsi.ttcn.tri.TriCommunicationSA#triUnmap(org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriPortId) - */ - @Override - public TriStatus triUnmap(final TriPortId compPortId, final TriPortId tsiPortId) { - - compPortMgr.removePort(compPortId.getComponent().getComponentId(), tsiPortId.getPortName()); - - return required.getTriStatus(TriStatus.TRI_OK); - } - - /** - * Enqueues a message on the specified port - * @param tsiPort Port where the message will be enqueued - * @param sutAddress SUT address - * @param receiverComp Component on which port the message will be enqueued - * @param rcvMessage Message to be enqueued - */ - private void enqueueMsg(TriPortId tsiPort, TriAddress sutAddress, TriComponentId receiverComp, TriMessage rcvMessage) { - - required.getCommunicationTE().triEnqueueMsg(tsiPort, sutAddress, receiverComp, rcvMessage); - } - - /* (non-Javadoc) - * @see java.util.Observer#update(java.util.Observable, java.lang.Object) - */ - @Override - public void update(Observable o, Object context) { - - if(context instanceof PortEvent) { - // Extract context - PortEvent p = (PortEvent)context; - TriPortId port = null; - TriComponentId compId = null; - - port = (TriPortId)compPortMgr.getPortId(p.getComponentName(), p.getPortName()); - compId = compPortMgr.getComponent(p.getComponentName()); - - // Enqueue message - if (port != null) { - enqueueMsg( - port, - required.getTriAddress(new byte[] { }), - compId, - required.getTriMessage(p.get_message())); - } - } - } // End of method update - - /** - * TriCall not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triCall(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddress, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList) - */ - @Override - public TriStatus triCall(TriComponentId componentId, TriPortId tsiPortId, TriAddress sutAddress, TriSignatureId signatureId, TriParameterList parameterList) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triCall not implemented"); - } - - /** - * TriCallBC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triCallBC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList) - */ - @Override - public TriStatus triCallBC(TriComponentId componentId, TriPortId tsiPortId, TriSignatureId signatureId, TriParameterList parameterList) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triCallBC not implemented"); - } - - /** - * TriCallMC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triCallMC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddressList, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList) - */ - @Override - public TriStatus triCallMC(TriComponentId componentId, TriPortId tsiPortId, TriAddressList sutAddresses, TriSignatureId signatureId, TriParameterList parameterList) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triCallMC not implemented"); - } - - /** - * triRaise not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triRaise(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddress, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriException) - */ - @Override - public TriStatus triRaise(TriComponentId componentId, TriPortId tsiPortId, TriAddress sutAddress, TriSignatureId signatureId, TriException exception) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triRaise not implemented"); - } - - /** - * triRaiseBC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triRaiseBC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriException) - */ - @Override - public TriStatus triRaiseBC(TriComponentId componentId, TriPortId tsitPortId, TriSignatureId signatureId, TriException exc) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triRaiseBC not implemented"); - } - - /** - * triRaiseMC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triRaiseMC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddressList, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriException) - */ - @Override - public TriStatus triRaiseMC(TriComponentId componentId, TriPortId tsitPortId, TriAddressList sutAddresses, TriSignatureId signatureId, TriException exc) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triRaiseMC not implemented"); - } - - /** - * triReply not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triReply(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddress, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList, org.etsi.ttcn.tri.TriParameter) - */ - @Override - public TriStatus triReply(TriComponentId componentId, TriPortId tsiPortId, TriAddress sutAddress, TriSignatureId signatureId, TriParameterList parameterList, TriParameter returnValue) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triReply not implemented"); - } - - /** - * triReplyBC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triReplyBC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList, org.etsi.ttcn.tri.TriParameter) - */ - @Override - public TriStatus triReplyBC(TriComponentId componentId, TriPortId tsiPortId, TriSignatureId signatureId, TriParameterList parameterList, TriParameter returnValue) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triReplyBCnot implemented"); - } - - /** - * triReplyMC not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triReplyMC(org.etsi.ttcn.tri.TriComponentId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriAddressList, org.etsi.ttcn.tri.TriSignatureId, org.etsi.ttcn.tri.TriParameterList, org.etsi.ttcn.tri.TriParameter) - */ - @Override - public TriStatus triReplyMC(TriComponentId componentId, TriPortId tsiPortId, TriAddressList sutAddresses, TriSignatureId signatureId, TriParameterList parameterList, TriParameter returnValue) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triReplyMC not implemented"); - } - - /** - * triSutActionInformal not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triSutActionInformal(java.lang.String) - */ - @Override - public TriStatus triSutActionInformal(String description) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triSutActionInformal not implemented"); - } - - /** - * triMapParam not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triMapParam(org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriParameterList) - */ - @Override - public TriStatus triMapParam(TriPortId compPortId, TriPortId tsiPortId, TriParameterList paramList) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triMapParam not implemented"); - } - - /** - * triUnmapParam not implemented - * @see org.etsi.ttcn.tri.TriCommunicationSA#triUnmapParam(org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriPortId, org.etsi.ttcn.tri.TriParameterList) - */ - @Override - public TriStatus triUnmapParam(TriPortId compPortId, TriPortId tsiPortId, TriParameterList paramList) { - return required.getTriStatus(TriStatus.TRI_ERROR, "triUnmapParam not implemented"); - } - - @Override - public TriStatus triExecuteTestCase(TriTestCaseId arg0, TriPortIdList arg1) { - // TODO Auto-generated method stub - return triExecuteTestcase(arg0, arg1); - } - - @Override - public TriStatus triGetStreamValue(TriComponentId arg0, TriPortId arg1, TriAddress arg2, TriMessage arg3) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TriStatus triSetStreamValue(TriComponentId arg0, TriPortId arg1, TriAddress arg2, TriMessage arg3) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TriStatus triStaticMap(TriPortId arg0, TriPortId arg1) { - // TODO Auto-generated method stub - return null; - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/UdpMultiplexer.java b/javasrc/adapter/org/etsi/its/adapter/UdpMultiplexer.java deleted file mode 100644 index 804b6734afdddf556864281fd4aad0d4461039ac..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/UdpMultiplexer.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.etsi.its.adapter; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.util.HashMap; -import java.util.Map; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.UdpMultiplexer; -import org.etsi.its.adapter.layers.Layer; - -public class UdpMultiplexer { - - /** - * Parameter name for UDP port destination - */ - public static final String UDP_PORT_KEY = "Udport"; - - public String UdpAddress = "10.200.1.101"; // FIXME Use a generic way to retrieve UDP settings - - public int UdpRecvPort = 18501; // FIXME Use a generic way to retrieve UDP settings - - public int UdpSendPort = 18502; // FIXME Use a generic way to retrieve UDP settings - - /** - * Unique instance of the factory - */ - private static final UdpMultiplexer instance = new UdpMultiplexer(); - - private Map clientsToMacs = new HashMap(); - - //private Map clientsToFrameTypes = new HashMap(); - - private HashMap clientsToLayers = new HashMap(); - - private DatagramSocket iutSocket; - private InetAddress iutAddress; - private int iutPort; - private Thread iutThread; - - /** - * Gets the unique factory instance - * @return UdpMultiplexer instance - */ - public static UdpMultiplexer getInstance(){ - return instance; - } - - public UdpMultiplexer() { - } - - public synchronized void register(Layer client, byte[] macAddress, short frameType) { - //TERFactory.getInstance().logDebug(">>>UdpMultiplexer.registering: " + frameType); - - if(clientsToMacs.isEmpty()) { - try { - iutAddress = InetAddress.getByName(UdpAddress); - //TERFactory.getInstance().logDebug("UdpIpLayer.register: IUT Address: " + iutAddress.getHostAddress()); - iutPort = UdpSendPort; - iutSocket = new DatagramSocket(UdpRecvPort); - iutThread = new UdpThread(iutSocket); - iutThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - // Register client - clientsToMacs.put(client.toString(), macAddress); - clientsToLayers.put(client.toString(), client); - //clientsToFrameTypes.put(client.toString(), frameType); - } - - public synchronized void unregister(Layer client) { - if(clientsToMacs.containsKey(client.toString())) { - clientsToMacs.remove(client.toString()); - //clientsToFrameTypes.remove(client.toString()); - clientsToLayers.remove(client.toString()); - - if(clientsToMacs.isEmpty()) { - iutSocket.close(); - iutThread.interrupt(); - try { - iutThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - - public byte[] send(Layer client, byte[] dest, byte[] payload, Map params) { - - if(clientsToMacs.containsKey(client.toString())) { - - DatagramPacket packet = null; - if(params.containsKey(UDP_PORT_KEY)) { - packet = new DatagramPacket(payload, payload.length, iutAddress, Integer.parseInt((String) params.get(UDP_PORT_KEY))); - } else { - packet = new DatagramPacket(payload, payload.length, iutAddress, iutPort); - } - try { - iutSocket.send(packet); - return packet.getData(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return null; - } - - private class UdpThread extends Thread { - - private DatagramSocket taSocket; - private boolean running = true; - - public UdpThread(DatagramSocket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - - while(running) { - try { - byte[] buf = new byte[4096]; - - // receive packet - DatagramPacket packet = new DatagramPacket(buf, buf.length); - taSocket.receive(packet); - - byte[] buffer = ByteHelper.extract(packet.getData(), packet.getOffset(), packet.getLength()); - if(buffer.length < 28) { - continue; - } - - Map lowerInfo = new HashMap(); - lowerInfo.put(Layer.RECEPTION_TIMESTAMP, System.currentTimeMillis()); - - // Dispatch - for (String mapKey : clientsToMacs.keySet()) { - clientsToLayers.get(mapKey).receive(buffer, lowerInfo); - } - } catch (IOException e) { - running = false; - } - } - } - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/AtspLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/AtspLayer.java deleted file mode 100644 index 01d5e3a82d00e8c8f2eab357dab41919b801d894..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/AtspLayer.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.ttcn.tci.CharstringValue; - -/** - * Implementation of ITS IICP layer - */ -public class AtspLayer extends Layer implements IEthernetSpecific { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public AtspLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - return super.send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - super.receive(message, lowerInfo); - } - -} // End of class AtspLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/BtpLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/BtpLayer.java deleted file mode 100644 index ee098d08bf8d3f69e31eb38ed74fe6e6ba2d0783..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/BtpLayer.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Implementation of ITS Basic Transport Protocol layer - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; - -/** - * Implementation of ITS Basic Transport Protocol layer - */ -public class BtpLayer extends Layer { - - /** - * Parameter name for BTP packet type - */ - public static final String BTP_TYPE = "BtpType"; - - /** - * Parameter name for BTP destination port - */ - public static final String BTP_DSTPORT = "BtpDstPort"; - - /** - * Parameter name for BTP source port - */ - public static final String BTP_SRCPORT = "BtpSrcPort"; - - /** - * Parameter name for BTP destination port information - */ - public static final String BTP_DSTPORTINFO = "BtpDstPortInfo"; - - /** - * BTP packet type A - */ - public static final int TYPE_A = 0; - - /** - * BTP packet type B - */ - public static final int TYPE_B = 1; - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public BtpLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - - // Destination Port (16 bits) - int dstPort; - try { - dstPort = (Integer)params.get(BTP_DSTPORT); - } - catch (NullPointerException e) { - dstPort = 0; - } - byte[] encapsulated = ByteHelper.intToByteArray(dstPort, 2); - - if(params.get(BTP_TYPE).equals(TYPE_A)) { - // Source Port (16 bits) - int srcPort; - try { - srcPort = (Integer)params.get(BTP_SRCPORT); - } - catch (NullPointerException e) { - srcPort = 0; - } - encapsulated = ByteHelper.concat(encapsulated, ByteHelper.intToByteArray(srcPort, 2)); - } - else { - // Destination port info (16 bits) - int dstPortInfo; - try { - dstPortInfo = (Integer)params.get(BTP_DSTPORTINFO); - } - catch (NullPointerException e) { - dstPortInfo = 0; - } - encapsulated = ByteHelper.concat(encapsulated, ByteHelper.intToByteArray(dstPortInfo, 2)); - } - - // Update params -// if(lowerLayerName != null && lowerLayerName.equals("GN")) { -// params.put(GnLayer.GN_NEXTHEADER, "BTP-A"); // TODO Alex to confirm removal -// } - - return super.send(ByteHelper.concat(encapsulated, message), params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - - byte[] dstPort = new byte[2]; - System.arraycopy(message, 0, dstPort, 0, 2); - - byte[] srcPort = new byte[2]; - System.arraycopy(message, 2, srcPort, 0, 2); - - int payloadLength = message.length - 4; - byte[] payload = new byte[payloadLength]; - System.arraycopy(message, 4, payload, 0, payloadLength); - - lowerInfo.put(BTP_DSTPORT, dstPort); - lowerInfo.put(BTP_DSTPORTINFO, srcPort); - - super.receive(payload, lowerInfo); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/CommsigniaLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/CommsigniaLayer.java deleted file mode 100644 index 22226ee1c6051c291864274c24f4c34a9163d829..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/CommsigniaLayer.java +++ /dev/null @@ -1,296 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; -import java.util.concurrent.TimeoutException; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.PcapMultiplexer; - -import com.commsignia.v2x.client.ITSApplication; -import com.commsignia.v2x.client.MessageSet; -import com.commsignia.v2x.client.exception.ClientException; -import com.commsignia.v2x.client.model.BTPType; -import com.commsignia.v2x.client.model.InjectData; -import com.commsignia.v2x.client.model.InjectData.Builder; -import com.commsignia.v2x.client.model.InjectData.Type; -import com.commsignia.v2x.client.model.dev.DeviceInfoResponse; -import com.commsignia.v2x.client.model.dev.FacilityModule; - -public class CommsigniaLayer extends Layer implements IEthernetSpecific { - - private static final byte[] DeviceMacAddress = new byte[] { (byte)0x70, (byte)0xb3, (byte)0xd5, (byte)0xf2, (byte)0xa1, (byte)0xe3 }; - private static final String TargetHost = "10.200.1.101"; - private static final int TargetPort = 7942; - private static final int SourcePort = 7943; - private static final int ItsAid = 5; - private static final int InterfaceID = 2; - private static final int TxPowerDbm = -32; // Max value: -33dBm, RSU: -30dBm, Lab: -10dBm - private static String pcapFilter = null; - - /** - * Well-known Ethernet broadcast address - */ - public static byte[] MAC_BROADCAST = new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; - - /** - * Parameter name for Link-Layer destination - */ - public static final String LINK_LAYER_DESTINATION = "LinkLayerDestination"; - - private Map ClientsToMacs = new HashMap(); - private Map ClientsToFrameTypes = new HashMap(); - private HashMap ClientsToLayers = new HashMap(); - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public CommsigniaLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - - MessageSet defaultMessageSet = MessageSet.C; - itsApplication = new ITSApplication(ItsAid, TargetHost, TargetPort, defaultMessageSet); - try { - itsApplication.connect(1000); - itsApplication.registerBlocking(); -// itsApplication.setFacilityModuleStatus(FacilityModule.BSM, false); -// itsApplication.setFacilityModuleStatus(FacilityModule.CAM, false); -// itsApplication. gnBindBlocking(BTPType.NONE, 65535); - } catch (TimeoutException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ClientException e) { - e.printStackTrace(); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - TERFactory.getInstance().logDebug(">>> CommsigniaLayer.register: " + upperLayer); - - if(registeredUpperLayer == null) { - super.register(upperLayer); - - try { - Method getEthernetType = registeredUpperLayer.getClass().getMethod("getEthernetType", (Class[])null); - if (getEthernetType != null) { - upperLayerFrameType = (Short) getEthernetType.invoke(registeredUpperLayer, (Object[]) null); - } - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - - localMacAddress = management.getLinkLayerAddress(); - PcapMultiplexer.getInstance().register(this, DeviceMacAddress, this.getEthernetType()); - } - - if(ClientsToMacs.isEmpty()) { - pcapFilter = - "udp dst port " + SourcePort + -// " and not ether[0x56:4]==0x04e54800 and not ether[0x56:4]==0x04f02122 and not ether[0x56:4]==0xa60e3f16 and not ether[0x56:4]==0x04e54800 and not ether[0x56:4]==0x92232f44 and not ether[0x56:4]==0x4a74556d" + - " and not ether[0x56:4]==0x4a74556d" + - " and "; - } else { - TERFactory.getInstance().logDebug("CommsigniaLayer.register: Another Client !"); - pcapFilter = pcapFilter + " and "; - } - // Update Filter - String strMacAddress = String.format("%02x%02x%02x%02x", localMacAddress[0], localMacAddress[1], localMacAddress[2], localMacAddress[3]); -// String strMacAddress = String.format("%02x", localMacAddress[0]); -// for(int i=1; i < localMacAddress.length; i++) { -// strMacAddress += String.format(":%02x", localMacAddress[i]); -// } - //udp dst port 7493 && wlan src 8b:ad:f0:0d:01:02 - pcapFilter = pcapFilter + "not ether[0x56:4]==0x" + strMacAddress; - // Reset filter - System.out.println("Reset PCAP filter: " + pcapFilter); - PcapMultiplexer.getInstance().resetFilter(pcapFilter); - // Register client - ClientsToMacs.put(this.toString(), localMacAddress); - ClientsToLayers.put(this.toString(), upperLayer); - ClientsToFrameTypes.put(this.toString(), upperLayerFrameType); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> CommsigniaLayer.receive: " + ByteHelper.byteArrayToString(message)); - - if (message.length <= 20+8+29+26) { // TODO To be refine - // Skip it - return; - } - ByteBuffer byteBuffer = ByteBuffer.wrap(message); - - // Skip C2P protocol - byteBuffer.position( - 20 + // IP Layer: 45 00 01 1f 13 8c 00 00 80 11 6b 0b ac 11 0f 26 ff ff ff ff - 8 + // UDP Layer: 75 30 1f 07 01 0b a6 cd - 34 + // C2P Layer: 12 00 00 33 41 00 00 03 5c ac 00 02 0c 02 35 a4 e9 01 6b 49 d2 01 3f ff 00 00 7f ff 16 - 4 // IEEE 802.11L Layer: 88 00 00 00 00 - ); - - // Extract Dst - byte[] dst = new byte[6]; - byteBuffer.get(dst, 0, dst.length); - lowerInfo.put(EthernetLayer.LINK_LAYER_DESTINATION, dst); - - // Skip Src - byteBuffer.position(byteBuffer.position() + 6); - - // Skip IEEE 802.11L Layer - byteBuffer.position(byteBuffer.position() + 10); - - // Skip LLC header - byteBuffer.position(byteBuffer.position() + 6); - - // Extract FrameType info - byte[] rawFrameType = new byte[2]; - byteBuffer.get(rawFrameType, 0, rawFrameType.length); - short frameType = ByteHelper.byteArrayToInt(rawFrameType).shortValue(); - - // Extract Data - byte[] data = new byte[byteBuffer.remaining()]; - byteBuffer.get(data, 0, byteBuffer.remaining()); - - // Dispatch - for (String mapKey : ClientsToMacs.keySet()) { - if(frameType == ClientsToFrameTypes.get(mapKey)) { - if(Arrays.equals(dst, MAC_BROADCAST) || Arrays.equals(dst, ClientsToMacs.get(mapKey))) { - ClientsToLayers.get(mapKey).receive(data, lowerInfo); - } - } - } - - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - //TERFactory.getInstance().logDebug(">>> CommsigniaLayer.send: " + ByteHelper.byteArrayToString(message)); - - byte[] dst = (byte[])params.get(LINK_LAYER_DESTINATION); - if(dst == null) { - dst = MAC_BROADCAST; - } - - byte[] packet = ByteHelper.concat( - dst, - localMacAddress, - ByteHelper.intToByteArray(upperLayerFrameType, 2), - message - ); - - try { - String dstAddress = String.format( - "%02x:%02x:%02x:%02x:%02x:%02x", - dst[0], - dst[1], - dst[2], - dst[3], - dst[4], - dst[5]); - String srcAddress = String.format( - "%02x:%02x:%02x:%02x:%02x:%02x", - localMacAddress[0], - localMacAddress[1], - localMacAddress[2], - localMacAddress[3], - localMacAddress[4], - localMacAddress[5]); - Builder build = new InjectData.Builder(); - build - .withDstAddress(dstAddress) - .withSrcAddress(srcAddress) - .withType(Type.GNP) - .withInterfaceID(InterfaceID) - .withTxPowerDbm(TxPowerDbm) - .withData(message); - InjectData injectData = build.build(); - //TERFactory.getInstance().logDebug("CommsigniaLayer.send: " + ByteHelper.byteArrayToString(injectData.getData())); - - itsApplication.sendOnRadioBlocking(injectData); - //TERFactory.getInstance().logDebug("<<< CommsigniaLayer.send: " + ByteHelper.byteArrayToString(packet)); - return true;//super.send(packet, params); - } catch (ClientException e) { - e.printStackTrace(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - return false; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - PcapMultiplexer.getInstance().unregister(this); - if(ClientsToMacs.containsKey(this.toString())) { - ClientsToMacs.remove(this.toString()); - ClientsToFrameTypes.remove(this.toString()); - ClientsToLayers.remove(this.toString()); - - if(ClientsToMacs.isEmpty()) { - if (itsApplication != null) { - try { -// itsApplication.gnCloseBlocking(BTPType.NONE, 65535); - itsApplication.deregisterBlocking(); - } catch (ClientException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - itsApplication.shutdown(); - itsApplication = null; - } - } - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - return (short)0x0800; - } - - /** - * Local Ethernet address - */ - private byte[] localMacAddress; - - /** - * Upper layer's frame type - */ - private short upperLayerFrameType; - - private ITSApplication itsApplication = null; - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/EthernetLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/EthernetLayer.java deleted file mode 100644 index 803e4902375ebc4f00daf3f530f5e7478a87ead3..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/EthernetLayer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Implementation of Ethernet layer using jpcap (background thread) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.PcapMultiplexer; - -/** - * Implementation of Ethernet layer using jpcap (background thread) - */ -public class EthernetLayer extends Layer { - - /** - * Well-known Ethernet broadcast address - */ - public static byte[] MAC_BROADCAST = new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; - - /** - * Parameter name for Link-Layer destination - */ - public static final String LINK_LAYER_DESTINATION = "LinkLayerDestination"; - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public EthernetLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - if(registeredUpperLayer == null) { - super.register(upperLayer); - - try { - Method getEthernetType = registeredUpperLayer.getClass().getMethod("getEthernetType", (Class[])null); - if (getEthernetType != null) { - upperLayerFrameType = (Short) getEthernetType.invoke(registeredUpperLayer, (Object[]) null); - } - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - - localMacAddress = management.getLinkLayerAddress(); - PcapMultiplexer.getInstance().register(this, localMacAddress, upperLayerFrameType); - - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - - byte[] dst = (byte[])params.get(LINK_LAYER_DESTINATION); - if(dst == null) { - dst = MAC_BROADCAST; - } - - byte[] sent = PcapMultiplexer.getInstance().sendPacket(this, dst, message); - - return super.send(sent, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - - PcapMultiplexer.getInstance().unregister(this); - } - - /** - * Local Ethernet address - */ - private byte[] localMacAddress; - - /** - * Upper layer's frame type - */ - private short upperLayerFrameType; - -} - diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/FntpLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/FntpLayer.java deleted file mode 100644 index 11455388efdbc24215c6074a249e0dc9c2c3c38c..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/FntpLayer.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.adapter.TERFactory; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.ttcn.tci.CharstringValue; - -/** - * Implementation of ITS FNTP layer - */ -public class FntpLayer extends Layer implements IEthernetSpecific { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public FntpLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - return super.send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - super.receive(message, lowerInfo); - } - -} // End of class FntpLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/FsapLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/FsapLayer.java deleted file mode 100644 index 1fb0745d9c24e255c7048102493adb85312458bf..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/FsapLayer.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.adapter.TERFactory; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.ttcn.tci.CharstringValue; - -/** - * Implementation of ITS FSAP layer - */ -public class FsapLayer extends Layer implements IEthernetSpecific { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public FsapLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - return super.send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - super.receive(message, lowerInfo); - } - -} // End of class FntpLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/G5Layer.java b/javasrc/adapter/org/etsi/its/adapter/layers/G5Layer.java deleted file mode 100644 index 58c66929d6075315e452916576bb41620f01f179..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/G5Layer.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Implementation of ITS G5 layer - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * Implementation of ITS G5 layer - */ -public class G5Layer extends Layer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public G5Layer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/GnLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/GnLayer.java deleted file mode 100644 index 13d4e8484eff6db92ff590b4d06d8115a2d4b4c1..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/GnLayer.java +++ /dev/null @@ -1,831 +0,0 @@ -/** - * Implementation of ITS GeoNetworking layer (background thread) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.ttcn.tci.CharstringValue; - -import de.fraunhofer.sit.c2x.CryptoLib; - -/** - * Implementation of ITS GeoNetworking layer (background thread) - */ -public class GnLayer extends Layer implements Runnable, IEthernetSpecific { - - /** - * Implemented version of GeoNetworking specification - */ - private static final int GN_VERSION = 0; - - /** - * Parameter name for GeoNetworking packet type - */ - public static final String GN_TYPE = "GnType"; - - /** - * Parameter name for GeoNetworking packet sub-type - */ - public static final String GN_SUBTYPE = "GnSubType"; - - /** - * Parameter name for GeoNetworking payload type - */ - public static final String GN_NEXTHEADER = "GnNextHeader"; - - /** - * Parameter name for destination position vector - */ - public static final String GN_DEPV = "GnDePV"; - - /** - * Parameter name for Location Service's Target GN_Address - */ - public static final String GN_TARGETGNADDR = "GnTargetGnAddress"; - - /** - * Parameter name for destination area's latitude - */ - public static final String GN_LATITUDE = "GnLatitude"; - - /** - * Parameter name for destination area's longitude - */ - public static final String GN_LONGITUDE = "GnLongitude"; - - /** - * Parameter name for destination area's distance A - */ - public static final String GN_DISTANCEA = "GnDistanceA"; - - /** - * Parameter name for destination area's distance B - */ - public static final String GN_DISTANCEB = "GnDistanceB"; - - /** - * Parameter name for destination area's angle - */ - public static final String GN_ANGLE = "GnAngle"; - - /** - * Parameter name for traffic class - */ - public static final String GN_TRAFFICCLASS = "GnTrafficClass"; - - /** - * Parameter name for packet's lifetime - */ - public static final String GN_LIFETIME = "GnLifetime"; - - /** - * GeoNetworking header type for unknown messages - */ - public static final int HT_ANY = 0; - - /** - * GeoNetworking header type for beacon messages - */ - public static final int HT_BEACON = 1; - - /** - * GeoNetworking header type for GeoUnicast messages - */ - public static final int HT_GEOUNICAST = 2; - - /** - * GeoNetworking header type for GeoAnycast messages - */ - public static final int HT_GEOANYCAST = 3; - - /** - * GeoNetworking header type for GeoBroadcast messages - */ - public static final int HT_GEOBROADCAST = 4; - - /** - * GeoNetworking header type for Topology-scoped broadcast messages - */ - public static final int HT_TSB = 5; - - /** - * GeoNetworking header type for Location Service messages - */ - public static final int HT_LS = 6; - - - /** - * Unspecified GeoNetworking header sub-type - */ - public static final int HST_UNSPECIFIED = 0; - - /** - * Circle sub-type for GeoBroadcast/GeoAnycast messages - */ - public static final int HST_CIRCLE = 0; - - /** - * Rectangle sub-type for GeoBroadcast/GeoAnycast messages - */ - public static final int HST_RECT = 1; - - /** - * Ellipse sub-type for GeoBroadcast/GeoAnycast messages - */ - public static final int HST_ELIPSE = 2; - - /** - * Single-hop sub-type for TSB messages - */ - public static final int HST_SINGLEHOP = 0; - - /** - * Multi-hop sub-type for TSB messages - */ - public static final int HST_MULTIHOP = 1; - - /** - * LS-Request sub-type for LS messages - */ - public static final int HST_LSREQUEST = 0; - - /** - * LS-Reply sub-type for LS messages - */ - public static final int HST_LSREPLY = 1; - - /** - * UTC ITS time reference: 01/01/2004 00:00:00 GMT - */ - private static final long ITS_REF_TIME = 1072915200000L; - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public GnLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - sequenceNumber = 0; - running = true; - beaconThread = new Thread(this); - beaconThread.start(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /** - * Thread function for sending periodic beacons - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - Map params = new HashMap(); - params.put(GN_TYPE, HT_BEACON); - while(running) { - if(management.getGnBeacon() != null) { - send(null, params); - } - try { - Thread.sleep(management.getGnBeaconInterval()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - if(running) { - running = false; - try { - beaconThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - super.unregister(upperLayer); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - //TERFactory.getInstance().logDebug(">>> GnLayer.send: " + ByteHelper.byteArrayToString(message)); - - byte [] extHdr = null; - int ht; - int hst; - int hoplimit = 255; - - try { - ht = (Integer)params.get(GN_TYPE); - } - catch (NullPointerException e) { - ht = HT_ANY; - } - - try { - hst = (Integer)params.get(GN_SUBTYPE); - } - catch (NullPointerException e) { - hst = HST_UNSPECIFIED; - } - - switch(ht) { - case HT_LS: - if(hst == HST_LSREPLY) { - extHdr = createLsReplyHeader((byte[])params.get(GN_DEPV)); - } - else { - extHdr = createLsRequestHeader((byte[])params.get(GN_TARGETGNADDR)); - } - break; - case HT_GEOUNICAST: - extHdr = createGeoUnicastHeader((byte[])params.get(GN_DEPV)); - break; - case HT_TSB: - if(hst == HST_MULTIHOP) { - extHdr = createTsbHeader(); - } - else { - hoplimit = 1; - extHdr = createShbHeader(); - } - break; - case HT_GEOBROADCAST: - case HT_GEOANYCAST: - extHdr = createGeoBroadcastHeader( - (Long)params.get(GN_LATITUDE), - (Long)params.get(GN_LONGITUDE), - (Integer)params.get(GN_DISTANCEA), - (Integer)params.get(GN_DISTANCEB), - (Integer)params.get(GN_ANGLE) - ); - } - - byte[] toBeSent = null; - byte[] basicHdr = createBasicHeader(); - byte[] commonHdr = createCommonHeader((String)params.get(GN_NEXTHEADER), ht, hst, (message == null)?0:message.length, hoplimit); - if (!management.isSecuredModeSet()) { // Secure mode disabled - toBeSent = ByteHelper.concat(basicHdr, commonHdr, extHdr, message); - } else { - toBeSent = createSecuredMessage(basicHdr, commonHdr, extHdr, message, params); - } - - //TERFactory.getInstance().logDebug("<<< GnLayer.send: " + ByteHelper.byteArrayToString(toBeSent)); - return super.send(toBeSent, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> GnLayer.receive: " + ByteHelper.byteArrayToString(message)); - - byte[] basicHdr = new byte[4]; - System.arraycopy(message, 0, basicHdr, 0, 4); - byte[] versionNh = new byte[1]; - System.arraycopy(basicHdr, 0, versionNh, 0, 1); - byte nextHeader = (byte)(versionNh[0] & (byte)0x0F); - int lt_multiplier = ((basicHdr[2] & (byte)0xFC) >> 2)&0x3F; - int lt_base = basicHdr[2] & (byte)0x03; - int lifetime = computeGnLifeTime(lt_multiplier, lt_base); - - if (nextHeader == 0x01) { // Common header - Secure mode disabled - byte[] commonHdr = new byte[8]; - System.arraycopy(message, 4, commonHdr, 0, 8); - nextHeader = (byte)((commonHdr[0] & (byte)0xF0) >> 4); - int trafficClass = (int)(commonHdr[2]); - - byte[] htHst = new byte[1]; - System.arraycopy(commonHdr, 1, htHst, 0, 1); - int headerSubType = (int)(htHst[0] & (byte)0x0F); - int headerType = (int)(htHst[0] >> 4); - - byte[] pl = new byte[2]; - System.arraycopy(commonHdr, 4, pl , 0, 2); - int payloadLength = ByteHelper.byteArrayToInt(pl); - - if(headerType == HT_LS) { - // Process LS messages - if(headerSubType == HST_LSREQUEST) { - byte[] gnAddress = new byte[8]; - System.arraycopy(message, 68, gnAddress, 0, 8); - byte[] mid = new byte[6]; - System.arraycopy(gnAddress, 2, mid, 0, 6); - if(Arrays.equals(mid, management.getLinkLayerAddress()) == true) { - // Send LS Reply - byte[] depv = new byte[20]; - System.arraycopy(message, 40, depv, 0, 20); - - Map params = new HashMap(); - params.put(GN_DEPV, depv); - params.put(GN_TYPE, HT_LS); - params.put(GN_SUBTYPE, HST_LSREPLY); - //TERFactory.getInstance().logDebug("GnLayer.receive: Send LS_REPLAY in unsecured mode"); - send(null, params); - } - } - else { - // we are not interested in LS replies so far. - } - } - else { - // Other messages - if(payloadLength > 0) { - byte[] mpayload = new byte[payloadLength]; - int extendedHeader = 0; - if (headerType == 1) { // Beacon - extendedHeader = 24; - } else if (headerType == 4) { // Geo Broadcast - extendedHeader = 44; - } else if (headerType == 5) { // Topology-Scoped Broadcast - extendedHeader = 28; - } // TODO To be continued - System.arraycopy(message, basicHdr.length + commonHdr.length + extendedHeader, mpayload, 0, payloadLength); - lowerInfo.put(GN_NEXTHEADER, nextHeader); - lowerInfo.put(GN_TYPE, headerType); - lowerInfo.put(GN_SUBTYPE, headerSubType); - lowerInfo.put(GN_LIFETIME, lifetime); - lowerInfo.put(GN_TRAFFICCLASS, trafficClass); - super.receive(mpayload, lowerInfo); - } - } - // Security disable, null will be translated into omit - lowerInfo.put(SecurityHelper.SEC_SSP, null); - lowerInfo.put(SecurityHelper.SEC_ITS_AID, null); - } else if (nextHeader == 0x02) { // Secured tag - byte[] payload = SecurityHelper.getInstance().checkSecuredProfileAndExtractPayload(message, basicHdr.length, management.isEnforceSecuredModeSet(), management.getItsAidOther(), lowerInfo); - if (payload != null) { - //TERFactory.getInstance().logDebug("GnLayer.receive: payload=" + ByteHelper.byteArrayToString(payload)); - byte[] commonHdr = new byte[8]; - System.arraycopy(payload, 0, commonHdr, 0, 8); - //TERFactory.getInstance().logDebug("GnLayer.receive: commonHdr=" + ByteHelper.byteArrayToString(commonHdr)); - nextHeader = (byte)((commonHdr[0] & (byte)0xF0) >> 4); - int trafficClass = (int)(commonHdr[2]); - - byte[] htHst = new byte[1]; - System.arraycopy(commonHdr, 1, htHst, 0, 1); - int headerType = (int)(htHst[0] >> 4); - int headerSubType = (int)(htHst[0] & 0x000000000F); - - byte[] pl = new byte[2]; - System.arraycopy(commonHdr, 4, pl , 0, 2); - int payloadLength = ByteHelper.byteArrayToInt(pl); - //TERFactory.getInstance().logDebug("GnLayer.receive: Message payload length=" + payloadLength); - - if(headerType == HT_LS) { - // Process LS messages - if(headerSubType == HST_LSREQUEST) { - int sopvPos = commonHdr.length + 3 + 8 + 3 * 4 + 2 * 2; // FIXME To be changed - byte[] gnAddress = new byte[8]; - System.arraycopy(message, sopvPos, gnAddress, 0, 8); - byte[] mid = new byte[6]; - System.arraycopy(gnAddress, 2, mid, 0, 6); - if(Arrays.equals(mid, management.getLinkLayerAddress()) == true) { - // Send LS Reply - byte[] depv = new byte[20]; - System.arraycopy(payload, sopvPos, depv, 0, 20); // FIXME Check indexes - - Map params = new HashMap(); - params.put(GN_DEPV, depv); - params.put(GN_TYPE, HT_LS); - params.put(GN_SUBTYPE, HST_LSREPLY); - //TERFactory.getInstance().logDebug("GnLayer.receive: Send LS_REPLAY in secured mode"); - send(null, params); - } - } else { - // we are not interested in LS replies so far. - } - } else { - // Other messages - if(payloadLength > 0) { - byte[] mpayload = new byte[payloadLength]; - int extendedHeader = 0; - if (headerType == 1) { // Beacon - extendedHeader = 24; - } else if (headerType == 4) { // Geo Broadcast - extendedHeader = 44; - } else if (headerType == 5) { // Topology-Scoped Broadcast - extendedHeader = 28; - } // TODO To be continued - System.arraycopy(payload, commonHdr.length + extendedHeader, mpayload, 0, payloadLength); - //TERFactory.getInstance().logDebug("GnLayer.receive: Message =" + ByteHelper.byteArrayToString(mpayload)); - lowerInfo.put(GN_NEXTHEADER, nextHeader); - lowerInfo.put(GN_TYPE, headerType); - lowerInfo.put(GN_SUBTYPE, headerSubType); - lowerInfo.put(GN_LIFETIME, lifetime); - lowerInfo.put(GN_TRAFFICCLASS, trafficClass); - super.receive(mpayload, lowerInfo); - } - } - } else { - // Drop it - // FIXME as long as the cert chain is not complete, it should not be seen as error -> raise CR - //TERFactory.getInstance().logError("GnLayer.receive: Invalid basic header type"); - return; - } - } - } // End of method receive - - /** - * Computes GN lifetime value - * @param lt_multiplier GN LT multiplier - * @param lt_base GN LT base - * @return GN lifetime value in ms - */ - private int computeGnLifeTime(int lt_multiplier, int lt_base) { - - final int[] base = {50, 1000, 10000, 100000}; - - return base[lt_base] * lt_multiplier; - } - - /** - * Builds encoded Basic Header - * @return Encoded Basic Header - */ - private byte[] createBasicHeader() { - // Version 4 bits - // NextHeader 4 bits - byte[] versionNh = new byte[1]; - int nh = 1; - - versionNh[0] = (byte)(GN_VERSION << 4); - versionNh[0] |= (byte)nh & 0x0F; - if (management.isSecuredModeSet()) { // Secure mode enabled - // Set nextHeader to secured - versionNh[0] &= 0xFE; - versionNh[0] |= 0x02; - } - - // Reserved 1 byte - byte[] reserved = new byte[]{(byte)0x00}; - - // Lifetime 1 byte - byte[] lifetime = new byte[]{(byte)0x2B}; - - // RHL 1 byte - byte[] rhl = new byte[]{(byte)0x01}; - - return ByteHelper.concat(versionNh, reserved, lifetime, rhl); - } - - /** - * Builds encoded Common Header - * @param nextHeader Payload type - * @param ht Packet type - * @param hst Packet sub-type - * @param msgLength Length of payload - * @return Encoded Common Header - */ - private byte[] createCommonHeader(String nextHeader, int ht, int hst, int msgLength, int hoplimit) { - - // Version 4 bits - // NextHeader 4 bits - byte[] nhReserved = new byte[1]; - int nh = 0; - if(nextHeader != null) { - if(nextHeader.equals("BTP-A")) { - nh = 1; - } - else if(nextHeader.equals("BTP-B")) { - nh = 2; - } - else if(nextHeader.equals("IPv6")) { - nh = 3; - } - } - nhReserved[0] = (byte)(nh << 4); - - // HeaderType 4 bits - // HeaderSubType 4 bits - byte[] htHst = new byte[1]; - htHst[0] = (byte)(ht << 4); - htHst[0] |= (byte)hst & 0x0F; - - // Traffic Class 1 byte - byte[] tc = new byte[]{(byte)0x00}; - - // Flags 1 byte - byte[] flags = new byte[]{(byte)0x00}; - - // PayloadLength 2 bytes - byte[] pl = ByteHelper.intToByteArray(msgLength, 2); - - // Maximum HopLimit 1 byte - byte[] mhl = ByteHelper.intToByteArray(hoplimit, 1); - - // Reserved 1 byte - byte[] reserved = new byte[]{(byte)0x00}; - - return ByteHelper.concat(nhReserved, htHst, tc, flags, pl, mhl, reserved); - } - - /** - * Builds self GN_Address based on link-layer address - * @return Encoded GN_Address - */ - private byte[] createMyGnAddress() { - int ssc = 208; // France - byte[] flags = new byte[2]; - flags[0] = (byte)(1 << 7); // Manual address - flags[0] |= (byte)(9 << 3); // Ordinary RSU - flags[0] |= (byte)(1 << 2); // Private - flags[0] |= (byte)(ssc >> 10); // SSC - flags[1] = (byte)ssc; // SSC - byte[] mid = management.getLinkLayerAddress(); - return ByteHelper.concat(flags, mid); - } - - /** - * Builds self long position vector - * @return Encoded long position vector - */ - private byte[] createMyLpv() { - - byte[] gn = createMyGnAddress(); // 8 bytes - // Timestamp is 1s older than current time to avoid sending beacons coming from the future (time sync between nodes) - byte[] tst = ByteHelper.intToByteArray((int)((System.currentTimeMillis() - ITS_REF_TIME) % (long)Math.pow(2,32) - 1000), 4); - byte[] latitude = management.getLatitude(); - byte[] longitude = management.getLongitude(); - byte[] speed = ByteHelper.intToByteArray(0, 2); - byte[] heading = ByteHelper.intToByteArray(0, 2); - return ByteHelper.concat(gn, tst, latitude, longitude, speed, heading); - } - - /** - * Builds GeoUnicast extension header - * @param depv Destination position vector (short position vector) - * @return Encoded GeoUnicast extension header - */ - private byte[] createGeoUnicastHeader(byte[] depv) { - byte[] tsb = createTsbHeader(); - return ByteHelper.concat(tsb, depv); - } - - /** - * Builds SHB extension header - * @return Encoded SHB extension header - */ - private byte[] createShbHeader() { - byte[] sopv = createMyLpv(); - byte[] reserved = ByteHelper.intToByteArray(0, 4); - return ByteHelper.concat(sopv, reserved); - } - - /** - * Builds TSB extension header - * @return Encoded TSB extension header - */ - private byte[] createTsbHeader() { - byte[] sn = ByteHelper.intToByteArray(sequenceNumber++ , 2); - byte[] reserved = ByteHelper.intToByteArray(0, 2); - byte[] sopv = createMyLpv(); - return ByteHelper.concat(sn, reserved, sopv); - } - - /** - * Builds GeoBroadcast extension header - * @param geoAreaLatitude Destination GeoArea's latitude - * @param geoAreaLongitude Destination GeoArea's longitude - * @param distanceA Destination GeoArea's distance A - * @param distanceB Destination GeoArea's distance B - * @param angle Destination GeoArea's angle - * @return Encoded GeoBroadcast extension header - */ - private byte[] createGeoBroadcastHeader(long geoAreaLatitude, long geoAreaLongitude, int distanceA, int distanceB, int angle) { - byte[] tsb = createTsbHeader(); - byte[] lat = ByteHelper.longToByteArray(geoAreaLatitude & 0xffffffffL, 4); - byte[] lng = ByteHelper.longToByteArray(geoAreaLongitude & 0xffffffffL, 4); - byte[] distA = ByteHelper.intToByteArray(distanceA, 2); - byte[] distB = ByteHelper.intToByteArray(distanceB, 2); - byte[] ang = ByteHelper.intToByteArray(angle, 2); - byte[] reserved = ByteHelper.intToByteArray(0, 2); - return ByteHelper.concat(tsb, lat, lng, distA, distB, ang, reserved); - } - - /** - * Builds LS Request extension header - * @param gnAddress Target GN_Address - * @return Encoded LS Request extension header - */ - private byte[] createLsRequestHeader(byte[] gnAddress) { - byte[] tsb = createTsbHeader(); - return ByteHelper.concat(tsb, gnAddress); - } - - /** - * Builds LS Reply extension header - * @param depv Destination position vector (short position vector) - * @return Encoded LS Reply extension header - */ - private byte[] createLsReplyHeader(byte[] depv) { - byte[] tsb = createTsbHeader(); - return ByteHelper.concat(tsb, depv); - } - - private byte[] createSecuredMessage(final byte[] basicHdr, final byte[] commonHdr, final byte[] extHdr, final byte[] message, Map params) { - //TERFactory.getInstance().logDebug(">>> GnLayer.createSecuredMessage"); - - // SecuredMessage payload length - int payloadLength = commonHdr.length + extHdr.length + message.length; - - // Build the generation time value - long curtime = System.currentTimeMillis(); - byte[] generationTime = ByteHelper.longToByteArray((long)(curtime - 1072915200000L) * 1000L, Long.SIZE / Byte.SIZE); // In microseconds - //TERFactory.getInstance().logDebug("GnLayer.createSecuredMessage: generationTime=" + ByteHelper.byteArrayToString(generationTime)); - // Build the payload to be signed - byte[] headersField = null; - boolean withCertificate = true; // FIXME Check that GnLayer is really used only for PICS_xxxM_RECEPTION tests. If so, always add AT certificate - if (withCertificate) { - headersField = ByteHelper.concat( - ByteHelper.concat( // SecuredMessage HeaderFields - new byte[] { - (byte)0x80, // signerInfo - (byte)0x02 // Certificate - }, - management.getAtCertificate(), // Hashed8 - new byte[] { - (byte)0x00, // generationTime - }, - generationTime // Time64 value - ) - ); - } else { - headersField = ByteHelper.concat( - ByteHelper.concat( // SecuredMessage HeaderFields - new byte[] { - (byte)0x80, // signerInfo - (byte)0x01 // Certificate digest with ecdsap256 - }, - management.getAtCertificateDigest(), // Hashed8 - new byte[] { - (byte)0x00, // generationTime - }, - generationTime // Time64 value - ) - ); - } - int its_aid = -1; - switch ((int) params.get(BtpLayer.BTP_DSTPORT)) { - case 2001: // CAM - its_aid = 36; - break; - case 2002: // DENM - its_aid = 37; - break; - case 2003: // MAPEM - its_aid = 137; - break; - case 2004: // SPATEM - its_aid = 138; - break; - case 2006: // IVIM - its_aid = 140; - break; - case 2007: // SREM/SSEM - // No break; - case 2008: - its_aid = 140; - break; - case 2010: - its_aid = 100; // FIXME Use the correct value - break; - } // End of 'switch' statement - if (its_aid == 36) { // CAM - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x05, // its-aid - (byte)its_aid // 36 = CAM - } - ); - } else if (its_aid == 37) { // DENM - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x03 // GenerationLocation - }, - management.getLatitude(), // Latitude - management.getLongitude(), // Longitude - new byte[] { (byte)0x00, (byte)0x00 }, // Elevation - new byte[] { - (byte)0x05, // its-aid - (byte)its_aid // 37 = DENM - } - ); - } else { // Add Its-Aid for Other profile - byte[] b; - if (its_aid < 128) { - b = new byte[] { (byte)its_aid }; - } else { - b = SecurityHelper.getInstance().size2tls(its_aid); - } - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x03 // GenerationLocation - }, - management.getLatitude(), // Latitude - management.getLongitude(), // Longitude - new byte[] { (byte)0x00, (byte)0x00 }, // Elevation - new byte[] { - (byte)0x05 // Its-aid - }, - b // Other profile - ); - } - byte[] payloadLengthTls = SecurityHelper.getInstance().size2tls(payloadLength); - byte[] headersFieldLength = null; - if (headersField.length < 127) { - headersFieldLength = new byte[] { (byte)headersField.length }; - } else { - headersFieldLength = SecurityHelper.getInstance().size2tls(headersField.length); - } - byte[] toBeSignedData = ByteHelper.concat( - new byte[] { // SecuredMessage version - (byte)0x02 // version - }, - headersFieldLength, // HeadersField length - headersField, // HeaderFields - new byte[] { // SecuredMessage Payloads - (byte)0x01, // Secured payload type: signed (1) - }, - payloadLengthTls, // Data payload length - commonHdr, - extHdr, - message, // End of SecuredMessage Payloads - new byte[] { (byte)0x43 }, // Signature length - new byte[] { (byte)0x01 } // Signature - ); - //TERFactory.getInstance().logDebug("GnLayer.createSecuredMessage: toBeSignedData=" + ByteHelper.byteArrayToString(toBeSignedData)); - - byte[] toBeSent = null; - try { - // Signed the data - byte[] signatureBytes = CryptoLib.signWithEcdsaNistp256WithSha256(toBeSignedData, management.getSigningPrivateKey()); - //TERFactory.getInstance().logDebug("GnLayer.createSecuredMessage: signatureBytes=" + ByteHelper.byteArrayToString(signatureBytes)); - // Add signature - toBeSent = ByteHelper.concat( - basicHdr, - toBeSignedData, - new byte[] { - (byte)0x00, // Public Key Alg: ecdsa nistp256 with sha256 (0) - (byte)0x02 // ECC Point Type: compressed lsb y-0 (2) - }, // Signature header - ByteHelper.extract(signatureBytes, 2, signatureBytes.length - 2) - ); - } catch (Exception e) { - e.printStackTrace(); - } - - //TERFactory.getInstance().logDebug("GnLayer.createSecuredMessage: toBeSent=" + ByteHelper.byteArrayToString(toBeSent)); - return toBeSent; - } - - /** - * Indicates whether the layer is still active. Setting this field to false will cause - * the beaconning thread to stop its execution. - */ - private boolean running; - - /** - * Beaconning thread instance. - */ - private Thread beaconThread; - - /** - * Packet sequence number. Incremented after sending each unicast packet - */ - private int sequenceNumber; -} - diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/IEthernetSpecific.java b/javasrc/adapter/org/etsi/its/adapter/layers/IEthernetSpecific.java deleted file mode 100644 index a685525b99109103639fa70e79f9f4c5c03fbb27..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/IEthernetSpecific.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Implementations of IUT specific settings for Ethernet support - * - * @author ETSI / STF424 - * @version $URL:$ - * $Id:$ - * - */ -package org.etsi.its.adapter.layers; - -/** - * Implementations of IUT specific settings for Ethernet support - */ -public interface IEthernetSpecific { - - /** - * Gets the Ethernet frame type for upper layer packets - * @return The Ethernet frame type value - */ - public short getEthernetType(); - -} // End of interface IEthernetSpecific diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/IicpLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/IicpLayer.java deleted file mode 100644 index 651b9f56a3dbbfb37bde246facd001065d7912f5..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/IicpLayer.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.adapter.TERFactory; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.ttcn.tci.CharstringValue; - -/** - * Implementation of ITS IICP layer - */ -public class IicpLayer extends Layer implements IEthernetSpecific { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public IicpLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - return super.send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - super.receive(message, lowerInfo); - } - -} // End of class FntpLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/Layer.java b/javasrc/adapter/org/etsi/its/adapter/layers/Layer.java deleted file mode 100644 index e988fc5515f0bc78a0f964b849fcf4604371fadb..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/Layer.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Layer abstract class implementing generic behaviour of a protocol layer - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * Layer abstract class implementing generic behaviour of a protocol layer - */ -public abstract class Layer { - - /** - * Parameter name for reception timestamp - */ - public static final String RECEPTION_TIMESTAMP = "ReceptionTimestamp"; - - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public Layer(IManagementLayers management, Stack lowerStack) { - this.management = management; - this.lowerStack = lowerStack; - this.initialized = false; - } - - /** - * Initialises lower stack - */ - protected void initialize() { - if(!initialized && lowerStack != null && !lowerStack.isEmpty()) { - lowerLayerName = lowerStack.pop(); - lowerLayer = LayerFactory.getInstance().createLayer(management, lowerLayerName, lowerStack); - lowerLayer.register(this); - } - initialized = true; - } - - /** - * Transmits a message to registered lower layer after encapsulation - * @param message Encoded message to be sent - * @param params Layer parameters for sending message - * @return true if send operation is successful, false otherwise - */ - public boolean send(byte[] message, Map params) { - if(lowerLayer != null) { - return lowerLayer.send(message, params); - } - return true; - } - - /** - * Callback method invoked by registered lower layer upon message reception from lower stack - * @param message Message received from lower layer - * @param lowerInfo Additional information transmitted by lower layers - * @param receptionTime Message reception time - */ - public void receive(byte[] message, Map lowerInfo) { - if(registeredUpperLayer != null) { - registeredUpperLayer.receive(message, lowerInfo); - } - } - - /** - * Registers an upper layer. - * This method will also cause current layer to initialise its lower stack - * Messages received from lower layer will now be transmitted to upper layer, if necessary - * @param upperLayer Instance of the upper layer - */ - public void register(Layer upperLayer) { - registeredUpperLayer = upperLayer; - initialize(); - } - - /** - * Unregisters upper layer. - * This method will also cause current layer to unregister from its lower layer - * @param upperLayer - */ - public void unregister(Layer upperLayer) { - registeredUpperLayer = null; - if(lowerLayer != null) { - lowerLayer.unregister(this); - } - } - - /** - * Name of the lower layer - */ - protected String lowerLayerName; - - /** - * Registered upper layer instance - */ - protected Layer registeredUpperLayer = null; - - /** - * Lower layer instance - */ - protected Layer lowerLayer = null; - - /** - * Management instance - */ - protected IManagementLayers management = null; - - /** - * Lower stack - */ - private Stack lowerStack; - - /** - * Set to true if lower stack has been initialised (true if layer is operational), false otherwise - */ - private boolean initialized; -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/LayerFactory.java b/javasrc/adapter/org/etsi/its/adapter/layers/LayerFactory.java deleted file mode 100644 index 65ec1c681038e61264ee90e80a268e7b455385a9..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/LayerFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Layer factory (Singleton) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers; - -import java.lang.reflect.Constructor; -import java.util.Map; -import java.util.Stack; -import java.util.TreeMap; - -import org.etsi.adapter.TERFactory; -import org.etsi.its.adapter.IManagementLayers; - -/** - * Layer factory (Singleton) - */ -public class LayerFactory { - - /** - * Unique instance of the factory - */ - private static LayerFactory instance = new LayerFactory(); - - /** - * List of the registered layer types - */ - protected Map> layers = new TreeMap>(); - - /** - * Private constructor (Singleton pattern) - */ - private LayerFactory() { - // Register the layers - layers.put("BTP", BtpLayer.class); - layers.put("GN", GnLayer.class); - layers.put("G5", G5Layer.class); - layers.put("ETH", EthernetLayer.class); - layers.put("UdpIp", UdpIpLayer.class); - layers.put("UdpIpCSG", UdpIpCommsigniaLayer.class); - layers.put("CSG", CommsigniaLayer.class); - layers.put("UdpIpMarben", UdpIpMarbenLayer.class); - -// layers.put("Loopback", LoopbackLayer.class); -// layers.put("Debug", DebugLayer.class); -// layers.put("CamSource", CamSourceLayer.class); -// layers.put("DenmSource", DenmSourceLayer.class); -// layers.put("GnSource", GnSourceLayer.class); -// layers.put("BtpSource", BtpSourceLayer.class); -// layers.put("Gn6Source", Gn6SourceLayer.class); - } - - /** - * Gets the unique factory instance - * @return LayerFactory instance - */ - public static LayerFactory getInstance(){ - return instance; - } - - /** - * Creates a port of the desired type - * @param management Layer management instance - * @param layerName Name of the layer - * @param lowerStack Lower protocol stack - * @return Protocol port instance - */ - public Layer createLayer(IManagementLayers management, String layerName, Stack lowerStack) { - //TERFactory.getInstance().logDebug(">>> LayerFactory.createLayer: " + layerName); - Layer layer = null; - Class[] ctorParams = {IManagementLayers.class, lowerStack.getClass()}; - - try { - Class cls = layers.get(layerName); - if (cls == null) { - throw new RuntimeException("No class registered under " + layerName); - } - Constructor ctor = cls.getConstructor(ctorParams); - layer = ctor.newInstance(management, lowerStack); - } catch (Exception ex) { - ex.printStackTrace(); - } - return layer; - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpCommsigniaLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpCommsigniaLayer.java deleted file mode 100644 index e49b590ceadad3d0a3a91f3f0f26c8b43ad2fe1d..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpCommsigniaLayer.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.UdpMultiplexer; - -public class UdpIpCommsigniaLayer extends UdpIpLayer { - - private static String UdpAddress = "80.98.62.165"; //"10.200.1.101"; // FIXME Use a generic way to retrieve UDP settings - - private static int UdpRecvPort = 18501; // FIXME Use a generic way to retrieve UDP settings - - private static int UdpSendPort = 18502; // FIXME Use a generic way to retrieve UDP settings - - private Map clientsToFrameTypes = new HashMap(); - - public UdpIpCommsigniaLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - UdpMultiplexer.getInstance().UdpAddress = UdpAddress; - UdpMultiplexer.getInstance().UdpRecvPort = UdpRecvPort; - UdpMultiplexer.getInstance().UdpSendPort = UdpSendPort; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - if(registeredUpperLayer == null) { - super.register(upperLayer); - // Workaround for Commsignia CAM send module - Map lowerInfo = new HashMap(); - lowerInfo.put(UdpMultiplexer.getInstance().UDP_PORT_KEY, new Integer(UdpRecvPort).toString()); - super.send(new byte[] { (byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA }, lowerInfo); - } else { - super.register(upperLayer); - } - clientsToFrameTypes.put(this.toString(), upperLayerFrameType); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - super.unregister(upperLayer); - clientsToFrameTypes.remove(this.toString(), upperLayerFrameType); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - //TERFactory.getInstance().logDebug("UdpIpLayer.send: " + ByteHelper.byteArrayToString(message)); - - byte[] dst = (byte[])params.get(LINK_LAYER_DESTINATION); - if(dst == null) { - dst = MAC_BROADCAST; - } - - byte[] buffer = ByteHelper.concat( - new byte[] { (byte) 0xe0 }, - localMacAddress, - dst, - ByteHelper.intToByteArray(message.length, Short.SIZE / Byte.SIZE) , - message - ); - - return super.send(buffer, params); - } - - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> UdpIpLayer.run: Receive packet from " + packet.getSocketAddress() + "/" + packet.getPort()); - - if (message.length < 36) { - // Skip it - return; - } - - ByteBuffer byteBuffer = ByteBuffer.wrap(message); - //TERFactory.getInstance().logDebug("UdpIpLayer.run: Receive packet from " + ByteHelper.byteArrayToString(byteBuffer.array())); - - // Skip IEEE 802.11L Layer: 88 00 00 00 00 - byteBuffer.position(4); - - // Extract Dst - byte[] dst = new byte[6]; - byteBuffer.get(dst, 0, dst.length); - lowerInfo.put(EthernetLayer.LINK_LAYER_DESTINATION, dst); - - // Skip Src - byteBuffer.position(byteBuffer.position() + 6); - - // Skip LLC header - byteBuffer.position(byteBuffer.position() + 16); - - // Extract FrameType info - byte[] rawFrameType = new byte[2]; - byteBuffer.get(rawFrameType, 0, rawFrameType.length); - short frameType = ByteHelper.byteArrayToInt(rawFrameType).shortValue(); - - if (clientsToFrameTypes.containsKey(this.toString())) { - if(frameType == clientsToFrameTypes.get(this.toString())) { - if(Arrays.equals(dst, MAC_BROADCAST) || Arrays.equals(dst, localMacAddress)) { - if(registeredUpperLayer != null) { - // Extract Data - byte[] data = new byte[byteBuffer.remaining() - 4]; // Remove CRC added by the device - byteBuffer.get(data, 0, byteBuffer.remaining() - 4); - - registeredUpperLayer.receive(data, lowerInfo); - } - } - } - } - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpLayer.java deleted file mode 100644 index afde6f35a3358772d78840c1f174323d245be8b9..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpLayer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Implementation of Udp layer using jpcap (background thread) - * - * @author ETSI / STF424 - * @version $URL: https://forge.etsi.org/svn/ITS/branches/STF517/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpLayer.java $ - * $Id: UdpIpLayer.java 2518 2016-09-02 05:27:47Z garciay $ - * - */ -package org.etsi.its.adapter.layers; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.UdpMultiplexer; - -/** - * Implementation of Udp layer using jpcap (background thread) - */ -public class UdpIpLayer extends Layer { - - /** - * Well-known Udp broadcast address - */ - public static byte[] MAC_BROADCAST = new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; - - /** - * Parameter name for Link-Layer destination - */ - public static final String LINK_LAYER_DESTINATION = "LinkLayerDestination"; - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public UdpIpLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - if(registeredUpperLayer == null) { - super.register(upperLayer); - - try { - Method getEthernetType = registeredUpperLayer.getClass().getMethod("getEthernetType", (Class[])null); - if (getEthernetType != null) { - upperLayerFrameType = (Short) getEthernetType.invoke(registeredUpperLayer, (Object[]) null); - } - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - - localMacAddress = management.getLinkLayerAddress(); - UdpMultiplexer.getInstance().register(this, localMacAddress, upperLayerFrameType); - - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - - byte[] dst = (byte[])params.get(LINK_LAYER_DESTINATION); - if(dst == null) { - dst = MAC_BROADCAST; - } - - byte[] sent = UdpMultiplexer.getInstance().send(this, dst, message, params); - - return super.send(sent, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - - UdpMultiplexer.getInstance().unregister(this); - } - - /** - * Local Udp address - */ - protected byte[] localMacAddress; - - /** - * Upper layer's frame type - */ - protected short upperLayerFrameType; - -} - diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpMarbenLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpMarbenLayer.java deleted file mode 100644 index c52cfb90e18bec5f8ae256e974a68306cc770b90..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/UdpIpMarbenLayer.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.etsi.its.adapter.layers; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.UdpMultiplexer; - -public class UdpIpMarbenLayer extends UdpIpLayer { - - // Marben 88:ceres 182:Jupiter VM32G - private static String UdpAddress = "192.168.7.182"; //"10.200.1.101"; // FIXME Use a generic way to retrieve UDP settings - - private static int UdpRecvPort = 3751; //18501; // FIXME Use a generic way to retrieve UDP settings - - private static int UdpSendPort = 3750; //18502; // FIXME Use a generic way to retrieve UDP settings - - private Map clientsToFrameTypes = new HashMap(); - - public UdpIpMarbenLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - UdpMultiplexer.getInstance().UdpAddress = UdpAddress; - UdpMultiplexer.getInstance().UdpRecvPort = UdpRecvPort; - UdpMultiplexer.getInstance().UdpSendPort = UdpSendPort; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - if(registeredUpperLayer == null) { - super.register(upperLayer); - // Workaround for Marben CAM send module - Map lowerInfo = new HashMap(); - lowerInfo.put(UdpMultiplexer.getInstance().UDP_PORT_KEY, new Integer(UdpRecvPort).toString()); - super.send(new byte[] { (byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA }, lowerInfo); - } else { - super.register(upperLayer); - } - clientsToFrameTypes.put(this.toString(), upperLayerFrameType); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - super.unregister(upperLayer); - clientsToFrameTypes.remove(this.toString(), upperLayerFrameType); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - System.out.println("UdpIpMarbenLayer.send: " + ByteHelper.byteArrayToString(message)); - - return super.send(message, params); // ML(Marben) : no lower header added - } - - public void receive(byte[] message, Map lowerInfo) { - - System.out.println("UdpIpMarbenLayer.run: Received packet " + ByteHelper.byteArrayToString(message)); - - lowerInfo.put(EthernetLayer.LINK_LAYER_DESTINATION, MAC_BROADCAST); - - registeredUpperLayer.receive(message, lowerInfo); // no MAC+LLC headers expected for Marben (ML) - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/BtpSourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/BtpSourceLayer.java deleted file mode 100644 index 2cd0a50ee8dee45d350fcada33ecf5c67d49ea46..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/BtpSourceLayer.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * BTP source pseudo layer. It forwards a BTP message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL: svn+ssh://vcs.etsi.org/TTCN3/TOOL/ITS_TestPlatform/trunk/javasrc/adapter/org/etsi/its/adapter/layers/test/CamSourceLayer.java $ - * $Id: CamSourceLayer.java 146 2011-04-21 11:33:57Z berge $ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.layers.GnLayer; - -/** - * BTP source pseudo layer. It forwards a BTP message to upper layer every second - */ -public class BtpSourceLayer extends SourceLayer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public BtpSourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - // Do not forget to modify line 40/41 when switching from BTP-A to BTP-B - //message = _btpa/*_btpb*/; - message = _btpb_payload/*_btpa_payload*/; - } - - @Override - public void run() { - while(running) { - MaplowerInfo = new HashMap(); - //lowerInfo.put(GnLayer.GN_NEXTHEADER, 1); // BTP-A - lowerInfo.put(GnLayer.GN_NEXTHEADER, 2); // BTP-B - super.receive(message, lowerInfo); - try { - Thread.sleep(SOURCE_INTERVAL); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * BTP A message - * - * This header causes a TC failure because of payload expected - */ - @SuppressWarnings("unused") - private byte[] _btpa = new byte[]{ - (byte)0x02, (byte)0x3c, // destinationPort: 572 - (byte)0x02, (byte)0x3b // sourcePort: 571 - }; - - /** - * BTP A message - */ - @SuppressWarnings("unused") - private byte[] _btpa_payload = new byte[]{ - (byte)0x02, (byte)0x3c, // destinationPort: 572 - (byte)0x02, (byte)0x3b, // sourcePort: 571 - (byte)0xde, (byte)0xce, (byte)0xa5, (byte)0xed - }; - - /** - * BTP B message - * - * This header causes a TC failure because of payload expected - */ - @SuppressWarnings("unused") - private byte[] _btpb = new byte[]{ - (byte)0x02, (byte)0x3c, // destinationPort: 572 - (byte)0x02, (byte)0x3d // destinationPortInfo: 573 - }; - - /** - * BTP B message - */ - private byte[] _btpb_payload = new byte[]{ - (byte)0x02, (byte)0x3c, // destinationPort: 572 - (byte)0x02, (byte)0x3d, // destinationPortInfo: 573 - (byte)0xbe, (byte)0xef, (byte)0xde, (byte)0xad - }; - -} // End of class BtpSourceLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/CamSourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/CamSourceLayer.java deleted file mode 100644 index 3430bdc014c3c6304ecaa3c107bfa1634b208977..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/CamSourceLayer.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * CAM source pseudo layer. It forwards a CAM message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * CAM source pseudo layer. It forwards a CAM message to upper layer every second - */ -public class CamSourceLayer extends SourceLayer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public CamSourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - //message = new byte[]{}; - } - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/DebugLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/DebugLayer.java deleted file mode 100644 index 8636b0a0937aa8af90b50cf7caea77c6d15f2a45..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/DebugLayer.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Pseudo layer that prints what it receives from upper layer - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.Map; -import java.util.Stack; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.layers.Layer; - -/** - * Pseudo layer that prints what it receives from upper layer - */ -public class DebugLayer extends Layer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public DebugLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - - ByteHelper.dump("Sending: ", message); - return true; - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/DenmSourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/DenmSourceLayer.java deleted file mode 100644 index 9daf9b6b2a39870a7bd44a7a635b878038ec1abf..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/DenmSourceLayer.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * DENM source pseudo layer. It forwards a DENM message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * DENM source pseudo layer. It forwards a DENM message to upper layer every second - */ -public class DenmSourceLayer extends SourceLayer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public DenmSourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - message = new byte[]{}; - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/Gn6SourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/Gn6SourceLayer.java deleted file mode 100644 index 55acda03a03c415e2236abe0266dba55b8f34db0..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/Gn6SourceLayer.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * GeoNetworking over IPv6 source pseudo layer. It forwards a BTP message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL: svn+ssh://vcs.etsi.org/TTCN3/TOOL/ITS_TestPlatform/trunk/javasrc/adapter/org/etsi/its/adapter/layers/test/CamSourceLayer.java $ - * $Id: CamSourceLayer.java 146 2011-04-21 11:33:57Z berge $ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * GeoNetworking over IPv6 source pseudo layer. It forwards a BTP message to upper layer every second - */ -public class Gn6SourceLayer extends SourceLayer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public Gn6SourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - // message = - } - - /** - * AcGn6InterfaceInfoList message - */ - @SuppressWarnings("unused") - private byte[] _acGn6InterfaceInfoList = new byte[]{ - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // Number of items - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0c, // Length of the interface name #0 - (byte)0x49, (byte)0x6e, (byte)0x74, (byte)0x65, (byte)0x72, (byte)0x66, (byte)0x61, (byte)0x63, (byte)0x65, (byte)0x20, (byte)0x23, (byte)0x30, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // Number of Ipv6Address - (byte)0x10, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x70, // Ipv6Address #1 - (byte)0x10, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x71, // Ipv6Address #2 - (byte)0x10, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x72, // Ipv6Address #3 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0c, // Length of the interface name #1 - (byte)0x49, (byte)0x6e, (byte)0x74, (byte)0x65, (byte)0x72, (byte)0x66, (byte)0x61, (byte)0x63, (byte)0x65, (byte)0x20, (byte)0x23, (byte)0x31, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // Number of Ipv6Address - (byte)0x20, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x70, // Ipv6Address #1 - (byte)0x20, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x71, // Ipv6Address #2 - (byte)0x20, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x72, // Ipv6Address #3 - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0c, // Length of the interface name #2 - (byte)0x49, (byte)0x6e, (byte)0x74, (byte)0x65, (byte)0x72, (byte)0x66, (byte)0x61, (byte)0x63, (byte)0x65, (byte)0x20, (byte)0x23, (byte)0x32, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, // Number of Ipv6Address - (byte)0x30, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x70, // Ipv6Address #1 - (byte)0x30, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x71, // Ipv6Address #2 - (byte)0x30, (byte)0x01, (byte)0x06, (byte)0x18, (byte)0x04, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x51, (byte)0x99, (byte)0xcc, (byte)0x72 // Ipv6Address #3 - }; - -} // End of class Gn6SourceLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/GnSourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/GnSourceLayer.java deleted file mode 100644 index b2542fc99dd1b5bb4f21f59a899fa5fa02f1e6f5..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/GnSourceLayer.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * GeoNetworking source pseudo layer. It forwards a GN message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; - -/** - * GeoNetworking source pseudo layer. It forwards a GN message to upper layer every second - */ -public class GnSourceLayer extends SourceLayer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public GnSourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - message = lsRequest/*beacon*/; - } - - /** - * Beacon message - */ - @SuppressWarnings("unused") - private byte[] beacon = new byte[]{ - // CommonHdr - (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xff, - // SEPV - // GN_ADDR - (byte)0xcc, (byte)0x2a, (byte)0xab, (byte)0xcd, - (byte)0xef, (byte)0xab, (byte)0xcd, (byte)0xe2, - // TST - (byte)0x4a, (byte)0x27, (byte)0x87, (byte)0x79, - // Lat - (byte)0x00, (byte)0x00, (byte)0x7e, (byte)0xca, - // Long - (byte)0x00, (byte)0x00, (byte)0x30, (byte)0xaa, - // Speed + Heading - (byte)0x00, (byte)0x00, (byte)0x30, (byte)0xaa, - // Alt + acc - (byte)0x00, (byte)0x00, (byte)0x30, (byte)0xaa - }; - - /** - * LS-Request - */ - private byte[] lsRequest = new byte[]{ - // CommonHdr - (byte)0x00, (byte)0x60, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF, - // SEPV - // GN_ADDR - (byte)0x00, (byte)0x42, (byte)0xDE, (byte)0xAD, - (byte)0xBE, (byte)0xEF, (byte)0x00, (byte)0x01, - // TST - (byte)0x54, (byte)0x84, (byte)0x75, (byte)0x10, - // Lat - (byte)0x42, (byte)0x54, (byte)0x00, (byte)0x00, - // Long - (byte)0x07, (byte)0x54, (byte)0x00, (byte)0x00, - // Speed + Heading - (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, - // Alt + acc - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - // SN + LT - (byte)0x00, (byte)0x42, (byte)0x33, (byte)0x00, - // SOPV - // GN_ADDR - (byte)0x00, (byte)0x42, (byte)0xDE, (byte)0xAD, - (byte)0xBE, (byte)0xEF, (byte)0x00, (byte)0x02, - // TST - (byte)0x54, (byte)0x84, (byte)0x75, (byte)0x10, - // Lat - (byte)0x42, (byte)0x54, (byte)0x00, (byte)0x00, - // Long - (byte)0x07, (byte)0x54, (byte)0x00, (byte)0x00, - // Speed + Heading - (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00, - // Alt + acc - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - // Target Gn_Address - (byte)0x00, (byte)0x42, (byte)0xDE, (byte)0xAD, - (byte)0xBA, (byte)0xBE, (byte)0xBE, (byte)0xEF - }; -} // End of class GnSourceLayer diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/LoopbackLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/LoopbackLayer.java deleted file mode 100644 index 9705cfb83e347c4cbc2079e4730e03e977863c0a..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/LoopbackLayer.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Pseudo layer that sends back what it receives from upper layer - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.Layer; - -/** - * Pseudo layer that sends back what it receives from upper layer - */ -public class LoopbackLayer extends Layer { - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public LoopbackLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - HashMap lowerInfo = new HashMap(); - lowerInfo.put(EthernetLayer.LINK_LAYER_DESTINATION, new byte[] {(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF}); - super.receive(message, lowerInfo); - return super.send(message, params); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/layers/test/SourceLayer.java b/javasrc/adapter/org/etsi/its/adapter/layers/test/SourceLayer.java deleted file mode 100644 index bbd40932019a5b3817643df3ebae72a8232c54aa..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/layers/test/SourceLayer.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Abstract class for packet source pseudo layers. It forwards a message to upper layer every second - * SHALL NOT BE INCLUDED IN RELEASE - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.layers.test; - -import java.util.HashMap; -import java.util.Stack; - -import org.etsi.its.adapter.IManagementLayers; -import org.etsi.its.adapter.layers.Layer; - -/** - * Abstract class for packet source pseudo layers. It forwards a message to upper layer every second - */ -public abstract class SourceLayer extends Layer implements Runnable { - - /** - * Default interval for sending messages - */ - protected static final long SOURCE_INTERVAL = 1000; - - /** - * Constructor - * @param management Layer management instance - * @param lowerStack Lower protocol stack - */ - public SourceLayer(IManagementLayers management, Stack lowerStack) { - super(management, lowerStack); - } - - /** - * Thread function for sending periodic messages - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - while(running) { - super.receive(message, new HashMap()); - try { - Thread.sleep(SOURCE_INTERVAL); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#register(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void register(Layer upperLayer) { - running = true; - sourceThread = new Thread(this); - sourceThread.start(); - super.register(upperLayer); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#unregister(org.etsi.its.adapter.layers.Layer) - */ - @Override - public void unregister(Layer upperLayer) { - if(running) { - running = false; - try { - sourceThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - super.unregister(upperLayer); - } - - /** - * Indicates whether the source is still active. Setting this field to false will cause - * the sending thread to stop its execution. - */ - protected boolean running; - - /** - * Sending thread instance. - */ - private Thread sourceThread; - - /** - * Message to be sent periodically - */ - protected byte[] message = "DUMMY".getBytes(); -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/AdapterControlPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/AdapterControlPort.java deleted file mode 100644 index cb767d45dd154dd3c31fa2b1943db1bfd899c731..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/AdapterControlPort.java +++ /dev/null @@ -1,345 +0,0 @@ -/** - * Adapter control port implementation for dynamic interactions with Test Adapter - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import org.etsi.adapter.GnssSupportFactory; -import org.etsi.adapter.IGnssSupport; -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.Management; -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tri.TriStatus; - -/** This class implements behaviour for Adapter controller port - * - */ - -public class AdapterControlPort extends AdapterPort implements IPort, IObservable { - - /* AdapterControl Primitives */ - private static final byte AcGnPrimitive = 0; - private static final byte AcGn6Primitive = 1; - private static final byte AcGnssPrimitive = 2; - private static final byte AcSecPrimitive = 3; - - /* AdapterControl Response */ - private static final byte AcGnResponse = 0; - //private static final byte AcGn6Response = 1; - public static final byte AcGnssResponse = 2; - public static final byte AcGnssDistanceCovered = 3; - public static final byte AcGnssTimeReached = 4; - public static final byte AcSecResponse = 5; - - /* GN Commands */ - private static final byte AcStartBeaconing = 0; - private static final byte AcStopBeaconing = 1; - private static final byte AcStartPassBeaconing = 2; - private static final byte AcStopPassBeaconing = 3; - private static final byte AcStartBeaconingMultipleNeighbour = 4; - private static final byte AcStopBeaconingMultipleNeighbour = 5; - private static final byte AcGetLongPosVector = 6; - - /* GN Responses */ - protected static final byte AcGnResponseFailure = 0; - protected static final byte AcLongPosVector = 6; - - /* SCENARIO commands */ - private static final byte AcLoadScenario = 0x70; - private static final byte AcStartScenario = 0x71; - private static final byte AcStopScenario = 0x72; - private static final byte AcAwaitDistanceToCover = 0x73; - private static final byte AcChangeSpead = 0x74; - private static final byte AcChangeHeading = 0x75; - private static final byte AcAwaitTimeInRunningScenario = 0x76; - - /* Set the certificate to be used by the Test Adapter */ - private static final byte AcEnableSecurity = 0x7a; - private static final byte AcDisableSecurity = 0x7b; - - - public static final byte AcTrue = 0x01; - public static final byte AcFalse = 0x00; - - private static final String GNSS_SCENARIO_SUPPORT = "GnssScenarioSupport"; - private IGnssSupport GNSS; - private boolean isScenarioStarted = false; - private boolean gnssScenarioSupport; - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - */ - public AdapterControlPort(final String portName, final String componentName) { - super(portName, componentName); - try { - gnssScenarioSupport = ((BooleanValue) TERFactory.getInstance().getTaParameter(GNSS_SCENARIO_SUPPORT)).getBoolean(); - } - catch (Throwable th) { - gnssScenarioSupport = false; - } - if (gnssScenarioSupport) { - GNSS = GnssSupportFactory.getInstance(); - } - } - - @Override - public boolean send(final byte[] message) { - - boolean result = true; - try { - // Decode non protocol part - switch(message[0]) { - case AcGnPrimitive: { - byte[] data = ByteHelper.extract(message, 2, message.length - 2); - switch (message[1]) { - case AcGetLongPosVector: - ProcessAcGetLongPosVector(data); - break; - case AcStartBeaconing: - Management.getInstance(getComponentName()).startBeaconing(data); - break; - case AcStopBeaconing: - Management.getInstance(getComponentName()).stopBeaconing(); - break; - case AcStartPassBeaconing: - Management.getInstance(getComponentName()).startEnqueueingBeacons(data); - break; - case AcStopPassBeaconing: - Management.getInstance(getComponentName()).stopEnqueueingBeacons(); - break; - case AcStartBeaconingMultipleNeighbour: - // TODO - break; - case AcStopBeaconingMultipleNeighbour: - // TODO - break; - } - } - break; - case AcGn6Primitive: - /* FIXME - try { - byte[] buf = new byte[4096]; - DatagramSocket remoteAdapterSocket = new DatagramSocket(); - InetAddress remoteAdapterAddress = InetAddress.getByName(((CharstringValue)TERFactory.getInstance().getTaParameter("Gn6RemoteAdapterIp")).getString()); - int remoteAdapterPort = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("Gn6RemoteAdapterPort")).getString()); - - DatagramPacket command = new DatagramPacket(new byte[] {CMD_IFACES}, 1, remoteAdapterAddress, remoteAdapterPort); - DatagramPacket response = new DatagramPacket(buf, buf.length); - - remoteAdapterSocket.send(command); - remoteAdapterSocket.receive(response); - - byte[] data = ByteHelper.extract(response.getData(), response.getOffset(), response.getLength()); - if(data[0] == RPL_IFACES) { - // enqueue response... - byte[] buffer = impl.Encode(TestAdapterMessageTypeEnum.AcGn6Response, ByteHelper.extract(data, 1, data.length - 1), new Date().getTime()); - setChanged(); - notifyObservers(new PortEvent(buffer, getPortName(), getComponentName())); - } - } catch (SocketException e) { - e.printStackTrace(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - */ - break; - case AcGnssPrimitive: - if (gnssScenarioSupport) { - byte[] data = ByteHelper.extract(message, 2, message.length - 2); - switch (message[1]) { - case AcLoadScenario: - LoadScenario(ByteHelper.byteArrayToShort(data)); - break; - case AcStartScenario: - StartScenario(); - break; - case AcStopScenario: - StopScenario(); - break; - case AcAwaitDistanceToCover: - Float distance = ByteHelper.byteArrayToFloat(data); - AwaitDistanceToCover(distance); - break; - case AcChangeSpead: -// ChangeSpeed(speed); - break; - case AcChangeHeading: -// ChangeHeading(heading); - break; - case AcAwaitTimeInRunningScenario: - int time = ByteHelper.byteArrayToInt(data); - AwaitTimeInRunningScenario(time); - break; - } - } - else { - TERFactory.getInstance().getTriStatus(TriStatus.TRI_OK, "AcGnssPrimitive cannot be handled as the " - + GNSS_SCENARIO_SUPPORT + " is set to false!"); - result = false; - } - break; - case AcSecPrimitive: - switch (message[1]) { - case AcEnableSecurity: - byte[] data = ByteHelper.extract(message, 2, message.length - 2); - ProcessAcEnableSecurity(data); - break; - case AcDisableSecurity: - ProcessAcDisableSecurity(); - break; - } // End of 'switch' statement - break; - default: - ByteHelper.dump("Unsupported AC primitive", message); - break; - } // End of 'switch' statement - - return result; - } catch (Exception e) { - e.printStackTrace(); - } - - return false; - } // End of method send - - /** - * Processes AcGetLongPosVector command - * @param data - */ - private void ProcessAcGetLongPosVector(final byte[] gnAddress) { - - new Thread(new Runnable() { - @Override - public void run() { - - byte[] response = null; - byte[] responseHdr = {(byte)AcGnResponse, (byte)0x00}; - byte[] longPosVector = Management.getInstance(getComponentName()).getLongPositionVector(gnAddress); - if((longPosVector == null) || (longPosVector.length == 0)) { - responseHdr[1] = (byte)AcGnResponseFailure; - response = ByteHelper.concat(responseHdr, new byte[]{AcTrue}); - } - else { - responseHdr[1] = (byte)AcLongPosVector; - response = ByteHelper.concat(responseHdr, longPosVector); - } - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void LoadScenario(final int scenario) { - new Thread(new Runnable() { - @Override - public void run() { - boolean result = GNSS.loadScenario(scenario); - byte[] response = {(byte)AcGnssResponse, (byte)(result?AcTrue:AcFalse)}; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void StartScenario() { - new Thread(new Runnable() { - @Override - public void run() { - isScenarioStarted = GNSS.startScenario(); - byte[] response = {(byte)AcGnssResponse, (byte)(isScenarioStarted?AcTrue:AcFalse)}; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void StopScenario() { - new Thread(new Runnable() { - @Override - public void run() { - boolean result = GNSS.stopScenario(); - isScenarioStarted = !result; - byte[] response = {(byte)AcGnssResponse, (byte)(isScenarioStarted?AcFalse:AcTrue)}; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void AwaitDistanceToCover(final double distance) { - new Thread(new Runnable() { - @Override - public void run() { - boolean result = GNSS.awaitDistanceToCover(AdapterControlPort.this, distance); - byte[] response = {(byte)AcGnssResponse, (byte)(result?AcFalse:AcTrue)}; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void AwaitTimeInRunningScenario(final int time) { - new Thread(new Runnable() { - @Override - public void run() { - boolean result = GNSS.awaitTimeInRunningScenario(AdapterControlPort.this, time); - byte[] response = {(byte)AcGnssResponse, (byte)(result?AcFalse:AcTrue)}; - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void ProcessAcEnableSecurity(final byte[] data) { - new Thread(new Runnable() { - @Override - public void run() { - Management.getInstance(getComponentName()).setSecuredMode(data); - byte[] response = {(byte)AcSecResponse, (byte)AcTrue }; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - private void ProcessAcDisableSecurity() { - new Thread(new Runnable() { - @Override - public void run() { - Management.getInstance(getComponentName()).unsetSecuredMode(); - byte[] response = {(byte)AcSecResponse, (byte)AcTrue }; - - setChanged(); - notifyObservers(new PortEvent(response, getPortName(), getComponentName())); - } - }).start(); - } - - - @Override - public void dispose() { - if (gnssScenarioSupport) { - if (GNSS!=null) { - if (isScenarioStarted) { - GNSS.stopScenario(); - } - GNSS.dispose(); - } - GNSS = null; - } - } - -} // End of class AdapterControlPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/AdapterPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/AdapterPort.java deleted file mode 100644 index 0791f31eae928cb9cfbb89ddcd2b46c495bb1abb..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/AdapterPort.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Abstract class for Adapter-related port implementations - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.Observable; -import java.util.Observer; - -/** - * Abstract class for Adapter-related port implementations - */ -public abstract class AdapterPort implements IPort, IObservable { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - */ - public AdapterPort(final String portName, final String componentName) { - this.portName = portName; - this.componentName = componentName; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#getPortName() - */ - @Override - public String getPortName() { - return portName; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#getComponentName() - */ - @Override - public String getComponentName() { - return componentName; - } - - /** - * Marks this Observable object as having been changed - */ - public void setChanged() { - observable.setChanged(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#notifyObservers(java.lang.Object) - */ - @Override - public void notifyObservers(Object arg) { - observable.notifyObservers(arg); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#addObserver(java.util.Observer) - */ - @Override - public void addObserver(Observer observer) { - observable.addObserver(observer); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#deleteObservers() - */ - @Override - public void deleteObservers() { - observable.deleteObservers(); - } - - /** - * Embedded object for implementing Observable behaviour - */ - private ObservablePort observable = new ObservablePort(); - - /** - * Name of the port - */ - private String portName; - - /** - * Name of the component owner; needed for enqueueing message - */ - private String componentName; - - /** - * Nested class for implementing Observable behaviour - */ - private class ObservablePort extends Observable implements IObservable { - - /* (non-Javadoc) - * @see java.util.Observable#setChanged() - */ - @Override - public void setChanged() { - super.setChanged(); - } - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/AtspPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/AtspPort.java deleted file mode 100644 index 5b1b5c64f127a9f229b33db3e89b25d706c1a03c..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/AtspPort.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.IEthernetSpecific; -import org.etsi.ttcn.tci.CharstringValue; - -public class AtspPort extends ProtocolPort implements IEthernetSpecific { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public AtspPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - // Encode with IicpInd indication header - // Extract LINK_LAYER_DESTINATION - byte[] iicpInd = ByteHelper.concat(message, (byte[])lowerInfo.get(EthernetLayer.LINK_LAYER_DESTINATION)); - super.receive(iicpInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - ByteHelper.dump("AtspPort.send", message); - HashMap params = new HashMap(); - return send(message, params); - } - - public boolean triggerInSapPrimitiveUp(byte[] inSapPrimitiveUp) { - ByteHelper.dump("AtspPort.triggerInSapPrimitiveUp", inSapPrimitiveUp); - HashMap params = new HashMap(); - params.put(EthernetLayer.LINK_LAYER_DESTINATION, management.getLinkLayerAddress()); - return send(inSapPrimitiveUp, params); - } - -} // End of class FntpPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/BtpPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/BtpPort.java deleted file mode 100644 index 6229e38c1420e22f807abc3e0bb4e2bb8aa40b36..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/BtpPort.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * BTP port implementation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -/** - * BTP port implementation - */ -public class BtpPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public BtpPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - - // Encode with GN next header info - BTP A or BTP B - byte[] msgInd = ByteHelper.concat( - new byte[] { ((Byte)(lowerInfo.get(GnLayer.GN_NEXTHEADER))).byteValue() }, - message - ); - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - switch (message[0]) { - case 1: - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_A); - params.put(GnLayer.GN_NEXTHEADER, "BTP-A"); - break; - case 2: - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - break; - default: - //otherwise GN next header is ANY - break; - } - params.put(BtpLayer.BTP_DSTPORT, 2001); - params.put(BtpLayer.BTP_SRCPORT, 500); - params.put(GnLayer.GN_TYPE, GnLayer.HT_TSB); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_MULTIHOP); - - byte[] msg2sent = new byte[message.length-1]; - //cut the next header indication byte - System.arraycopy(message, 1, msg2sent, 0, msg2sent.length); - - return send(msg2sent, params); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/CamPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/CamPort.java deleted file mode 100644 index b8fe4bfd32cc8ac6f72c73fd806851f885692f18..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/CamPort.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * CAM port implementation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -/** - * CAM port implementation - */ -public class CamPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public CamPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[], java.util.Map) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { -// TERFactory.getInstance().logDebug(">>> CamPort.receive: " + ByteHelper.byteArrayToString(message)); - - if (message[1] != 0x02) { // Check that received packet has CAM message id - See ETSI TS 102 894 - TERFactory.getInstance().logDebug("CamPort.receive: drop packet " + ByteHelper.byteArrayToString(message)); - return; // Drop it - } - - // Encode with CAM indication header - byte[] msgInd = ByteHelper.concat( - message, - new byte[] { (Byte) lowerInfo.get(GnLayer.GN_NEXTHEADER) }, - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_SUBTYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_LIFETIME), Integer.SIZE / Byte.SIZE), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TRAFFICCLASS), 1), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORT), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORTINFO) - ); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - params.put(BtpLayer.BTP_DSTPORT, 2001); - params.put(BtpLayer.BTP_SRCPORT, 500); - params.put(GnLayer.GN_TYPE, GnLayer.HT_TSB); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_SINGLEHOP); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - return send(message, params); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/ConfigTesterPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/ConfigTesterPort.java deleted file mode 100644 index 1c3f081c809dc6c3635720f3da361ad94fcee9ed..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/ConfigTesterPort.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.etsi.its.adapter.ports; - -/** - * Upper Tester port implementation. This port is used to trigger IUT's upper interface - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.CharstringValue; - -/** This class implements behaviour for Configuration Tester port. This port is used to access to the IUT management port - * The Configuration tester entity in the SUT enables triggering Protocol functionalities by simulating primitives from - * from SAPs - * It is required to trigger the Protocol layer in the SUT to send Protocol specific messages, which are - * resulting from management layer primitives - */ -public class ConfigTesterPort extends AdapterPort implements IPort, IObservable { - - private static final String SETTINGS_PATTERN = "(\\S+)\\:(\\d+)"; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param localPortNumber Local port number for the UDP listener - * @param remotePortNumber UDP port listener of remote UT application - */ - public ConfigTesterPort(final String portName, final String componentName) { - super(portName, componentName); - - // UDP connection parameters - String settings = ((CharstringValue)TERFactory.getInstance().getTaParameter("ConfigTesterSettings")).getString(); - Matcher matcher = settingsPattern.matcher(settings); - if (matcher.find()) { - try { - cfPeerAddress = InetAddress.getByName(matcher.group(1)); - } catch (UnknownHostException e1) { - e1.printStackTrace(); - } - cfPeerPort = Integer.parseInt(matcher.group(2)); - } else { - // FIXME - } - - // UDP socket for communication with Configuration module - running = true; - try { - cfSocket = new DatagramSocket(cfPeerPort + 1); - cfThread = new UdpThread(cfSocket); - cfThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public boolean send(final byte[] message) { - try { - ByteArrayOutputStream dataToSent = new ByteArrayOutputStream(); - dataToSent.write(message); - byte[] output = dataToSent.toByteArray(); - DatagramPacket packet = new DatagramPacket(output, output.length, cfPeerAddress, cfPeerPort); - cfSocket.send(packet); - - return true; - } catch (Exception e) { - e.printStackTrace(); - } - - return false; - } - - @Override - public void dispose() { - if(running) { - running = false; - if(cfThread != null) { - try { - cfSocket.close(); - cfThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - - private DatagramSocket cfSocket; - private Thread cfThread; - private InetAddress cfPeerAddress = null; - private int cfPeerPort = 0; - private Pattern settingsPattern = Pattern.compile(SETTINGS_PATTERN); - - /** - * Indicates whether the port is still active. Setting this field to false will cause - * the UDP communication with Upper Tester to be stopped - */ - private volatile boolean running; - - private class UdpThread extends Thread { - - private DatagramSocket taSocket; - - public UdpThread(DatagramSocket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - - while(running) { - try { - byte[] buf = new byte[4096]; - - // receive packet - DatagramPacket packet = new DatagramPacket(buf, buf.length); - taSocket.receive(packet); - - setChanged(); - notifyObservers(new PortEvent(ByteHelper.extract(packet.getData(), packet.getOffset(), packet.getLength()), getPortName(), getComponentName())); - } catch (IOException e) { - running = false; - } - } - taSocket.close(); - } - - } // End of class UdpThread - -} // End of class ConfigTesterPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/DenmPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/DenmPort.java deleted file mode 100644 index 9ef087f76ceadfd8e8b422ea803f632c5d11f3b1..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/DenmPort.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * DENM port implementation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -/** - * DENM port implementation - */ -public class DenmPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public DenmPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[], java.util.Map) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { -// TERFactory.getInstance().logDebug(">>> DenmPort.receive: " + ByteHelper.byteArrayToString(message)); - - if (message[1] != 0x01) { // Check that received packet has DENM message id - See ETSI TS 102 894 - TERFactory.getInstance().logDebug("DenmPort.receive: drop packet " + ByteHelper.byteArrayToString(message)); - return; // Drop it - } - - // Encode with DENM indication header - byte[] msgInd = ByteHelper.concat( - message, - new byte[] { (Byte) lowerInfo.get(GnLayer.GN_NEXTHEADER) }, - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_SUBTYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_LIFETIME), Integer.SIZE / Byte.SIZE), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TRAFFICCLASS), 1), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORT), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORTINFO) - ); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - params.put(BtpLayer.BTP_DSTPORT, 2002); - params.put(BtpLayer.BTP_SRCPORT, 500); -// params.put(GnLayer.GN_TYPE, GnLayer.HT_TSB); -// params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_SINGLEHOP); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - - params.put(GnLayer.GN_TYPE, GnLayer.HT_GEOBROADCAST); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_ELIPSE); - params.put(GnLayer.GN_LATITUDE, ByteHelper.byteArrayToLong(management.getLatitude())); - params.put(GnLayer.GN_LONGITUDE, ByteHelper.byteArrayToLong(management.getLongitude())); - params.put(GnLayer.GN_DISTANCEA, 200); - params.put(GnLayer.GN_DISTANCEB, 200); - params.put(GnLayer.GN_ANGLE, 0); -// - return send(message, params); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/FntpPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/FntpPort.java deleted file mode 100644 index 99e482917a35a6d4391c0c0aeee6e5e142a55288..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/FntpPort.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.IEthernetSpecific; -import org.etsi.ttcn.tci.CharstringValue; - -public class FntpPort extends ProtocolPort implements IEthernetSpecific { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public FntpPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - // Encode with FntpInd indication header - // Extract LINK_LAYER_DESTINATION - byte[] fntpInd = ByteHelper.concat(message, (byte[])lowerInfo.get(EthernetLayer.LINK_LAYER_DESTINATION)); - super.receive(fntpInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - ByteHelper.dump("FntpPort.send", message); - HashMap params = new HashMap(); - return send(message, params); - } - - public boolean triggerInSapPrimitiveUp(byte[] inSapPrimitiveUp) { - ByteHelper.dump("FntpPort.triggerInSapPrimitiveUp", inSapPrimitiveUp); - HashMap params = new HashMap(); - params.put(EthernetLayer.LINK_LAYER_DESTINATION, management.getLinkLayerAddress()); - return send(inSapPrimitiveUp, params); - } - -} // End of class FntpPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/FsapPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/FsapPort.java deleted file mode 100644 index 1d112b5c376620514e7cfc24b8ff9a2c50427b24..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/FsapPort.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.IEthernetSpecific; -import org.etsi.ttcn.tci.CharstringValue; - -public class FsapPort extends ProtocolPort implements Runnable, IEthernetSpecific { - - private volatile boolean _running; - - /** - * Service Provider thread instance. - */ - private Thread _beaconThread; - - private byte[] _sam; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public FsapPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - management.registerFsapPort(this); - _running = false; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - // Encode with FsapInd indication header - // Extract LINK_LAYER_DESTINATION - byte[] fsapInd = ByteHelper.concat(message, (byte[])lowerInfo.get(EthernetLayer.LINK_LAYER_DESTINATION)); - super.receive(fsapInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - ByteHelper.dump("FsapPort.send", message); - HashMap params = new HashMap(); - return send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#dispose() - */ - @Override - public void dispose() { - if(_running && _beaconThread != null) { - _running = false; - try { - _beaconThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - _sam = null; - super.dispose(); - } - - public boolean startSamTransmission(final byte[] sam) { - ByteHelper.dump("FsapPort.startSamTransmission", sam); - - _sam = sam.clone();//ByteHelper.extract(sam, 2, sam.length - 2); - if(_beaconThread == null) { - _beaconThread = new Thread(this); - _beaconThread.start(); - } - - return true; - } - - public boolean stopSamTransmission() { - _running = false; - try { - _beaconThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - _sam = null; - - return true; - } - - @Override - public void run() { - HashMap params = new HashMap(); - params.put(EthernetLayer.LINK_LAYER_DESTINATION, management.getLinkLayerAddress()); - _running = true; - while (_running) { - send(_sam, params); - try { - Thread.sleep(3000); // 3 second - } catch (InterruptedException e) { - - } - } // End of 'while' statement - - - } - -} // End of FntpPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/Gn6Port.java b/javasrc/adapter/org/etsi/its/adapter/ports/Gn6Port.java deleted file mode 100644 index 140fe00b71de796a8fac295121410b23c26f84f9..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/Gn6Port.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * GN6 port implementation - * - * @author ETSI / STF424 - * @version $URL: svn+ssh://vcs.etsi.org/TTCN3/TOOL/ITS_TestPlatform/trunk/javasrc/adapter/org/etsi/its/adapter/ports/CamPort.java $ - * $Id: CamPort.java 203 2011-05-03 09:17:50Z berge $ - * - */ -package org.etsi.its.adapter.ports; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.Layer; -import org.etsi.ttcn.tci.CharstringValue; - -/** - * CAM port implementation - */ -public class Gn6Port extends ProtocolPort implements Runnable { - - private static final byte CMD_REGISTER = 0x01; - private static final byte CMD_UNREGISTER = 0x02; - private static final byte CMD_PACKET = 0x04; - - private static final byte RPL_PACKET = 0x04; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public Gn6Port(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - - try { - remoteAdapterSocket = new DatagramSocket(); - remoteAdapterAddress = InetAddress.getByName(((CharstringValue)TERFactory.getInstance().getTaParameter("Gn6RemoteAdapterIp")).getString()); - remoteAdapterPort = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("Gn6RemoteAdapterPort")).getString()); - } catch (SocketException e) { - e.printStackTrace(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - running = true; - - // Start reception Thread - receptionThread = new Thread(this); - receptionThread.start(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - HashMap params = new HashMap(); - - int ipv6pos = ByteHelper.byteArrayToInt(new byte[] {message[0]}) + 12 + 1; - byte [] parameters = ByteHelper.extract(message, 0, ipv6pos); - byte [] ipv6 = ByteHelper.extract(message, ipv6pos, message.length - ipv6pos); - - byte [] sent = ByteHelper.concat(new byte[] {CMD_PACKET}, parameters, ByteHelper.intToByteArray(ipv6.length, 2), ipv6); - DatagramPacket packet = new DatagramPacket(sent, sent.length, remoteAdapterAddress, remoteAdapterPort); - try { - remoteAdapterSocket.send(packet); - } catch (IOException e) { - e.printStackTrace(); - } - - return send(sent, params); - } - - /** - * Thread function for sending periodic beacons - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - - byte[] buf = new byte[4096]; - byte[] data; - - // Send REGISTER to remote adapter - DatagramPacket command = new DatagramPacket(new byte[] {CMD_REGISTER}, 1, remoteAdapterAddress, remoteAdapterPort); - DatagramPacket response = new DatagramPacket(buf, buf.length); - try { - remoteAdapterSocket.send(command); - remoteAdapterSocket.receive(response); - } catch (IOException e) { - e.printStackTrace(); - } - - // Process messages from remote adapter - try { - remoteAdapterSocket.setSoTimeout(1000); - } catch (SocketException e1) { - e1.printStackTrace(); - } - while(running) { - - Map lowerInfo = new HashMap(); - try { - // receive packet - remoteAdapterSocket.receive(response); - } catch (SocketTimeoutException e) { - // ignore - continue; - } catch (IOException e) { - running = false; - } - - data = ByteHelper.extract(response.getData(), response.getOffset(), response.getLength()); - if(data[0] == RPL_PACKET) { - ByteHelper.dump("GN6 receive", data); - lowerInfo.put(Layer.RECEPTION_TIMESTAMP, System.currentTimeMillis()); - receive(ByteHelper.extract(data, 1, data.length - 1), lowerInfo); - } - } - - // Send UNREGISTER to remote adapter - command = new DatagramPacket(new byte[] {CMD_UNREGISTER}, 1, remoteAdapterAddress, remoteAdapterPort); - response = new DatagramPacket(buf, buf.length); - try { - remoteAdapterSocket.send(command); - remoteAdapterSocket.receive(response); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#dispose() - */ - @Override - public void dispose() { - if(running && receptionThread != null) { - running = false; - try { - receptionThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - super.dispose(); - } - - /** - * Indicates whether the port is still active. Setting this field to false will cause - * the reception thread to stop its execution. - */ - private volatile boolean running; - - /** - * Reception thread instance. - */ - private Thread receptionThread = null; - - private volatile DatagramSocket remoteAdapterSocket; - private InetAddress remoteAdapterAddress; - private int remoteAdapterPort; -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/GnPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/GnPort.java deleted file mode 100644 index a95528960367670262492cc08c792088af54cb3d..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/GnPort.java +++ /dev/null @@ -1,523 +0,0 @@ -/** - * GeoNetworking port implementation (background thread) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.IEthernetSpecific; -import org.etsi.ttcn.tci.CharstringValue; - -import de.fraunhofer.sit.c2x.CryptoLib; - -/** - * GeoNetworking port implementation (background thread) - */ -public class GnPort extends ProtocolPort implements Runnable, IEthernetSpecific { - - /** - * GeoNetworking header type for beacon messages - */ - private static final int HT_BEACON = 1; - private static final int HT_TSB = 5; - private static final int HST_SHB = 0; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public GnPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - running = true; - management.registerGnPort(this); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /** - * Starts beaconning - */ - public void startBeaconning() { - running = true; - if(beaconThread == null) { - beaconThread = new Thread(this); - beaconThread.start(); - } - } - - /** - * Stops beaconning - */ - public void stopBeaconning() { - if(beaconThread != null) { - running = false; - try { - beaconThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - beaconThread = null; - } - } - - /** - * Thread function for sending periodic beacons - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - byte[] beaconHeader = management.getGnBeacon(); - if(beaconHeader != null) { - long modulo = (long)Math.pow(2,32); - Map params = new HashMap(); -// long triggerTime = System.currentTimeMillis(); - while(running) { - // Update timestamp. Timestamp is 1s older than current time to avoid sending beacons coming from the future (time sync between nodes) - long currentTime = System.currentTimeMillis(); - byte[] tst = ByteHelper.intToByteArray((int)(((currentTime - 1072915200000L) % modulo) - 3000), 4); - System.arraycopy(tst, 0, beaconHeader, 20, 4); - if (!management.isSecuredModeSet()) { // Secure mode disabled - send(beaconHeader, params); - } else { // Send a secured beacon - byte[] securedBeaconHeader = buildSecuredBeacon(beaconHeader, tst, currentTime, false); -// triggerTime = currentTime; - // Send the secured beacon - //TERFactory.getInstance().logDebug("GnPort: Call send " + ByteHelper.byteArrayToString(securedBeaconHeader)); - send(securedBeaconHeader, params); - } - try { - Thread.sleep(management.getGnBeaconInterval()); - } catch (InterruptedException e) { - // Do nothing, we do not care - } - } - } - } - - private byte[] buildSecuredBeacon(final byte[] p_beacon, byte[] p_tst, final long p_currentTime, final boolean p_sendDigest) { - //TERFactory.getInstance().logDebug("GnPort.buildSecuredBeacon (1): " + ByteHelper.byteArrayToString(p_beacon)); - - byte[] basicHeader = ByteHelper.extract(p_beacon, 0, 4); - basicHeader[0] &= 0xFE; - basicHeader[0] |= 0x02; // Secured mode - - // Basic Header is not part of signed data - byte[] beacon = ByteHelper.extract(p_beacon, 4, p_beacon.length - 4); - //TERFactory.getInstance().logDebug("GnPort.buildSecuredBeacon (2): " + ByteHelper.byteArrayToString(beacon)); - // Prepare the message to be signed - byte[] toBeSignedData = buildToBeSignedData(beacon, p_currentTime, p_sendDigest); - //TERFactory.getInstance().logDebug("GnPort.buildSecuredBeacon: toBeSignedData " + ByteHelper.byteArrayToString(toBeSignedData)); - // Sign the message - byte[] securedBeaconHeader = signSecuredMessage(toBeSignedData); - - // Return the complete message to be sent - return ByteHelper.concat(basicHeader, securedBeaconHeader); - } - - private byte[] buildToBeSignedData(final byte[] p_beacon, final long p_currentTime, final boolean p_sendDigest) { - //TERFactory.getInstance().logDebug("GnPort.buildToBeSignedData: " + ByteHelper.byteArrayToString(p_beacon)); - - // Build the SignerInfo field - byte[] signerInfo = null; - if (!p_sendDigest) { - signerInfo = ByteHelper.concat( - new byte[] { - (byte)0x80, // signerInfo - (byte)0x02 // Certificate - }, - management.getAtCertificate() // Certificate value - ); - } else { - signerInfo = ByteHelper.concat( - new byte[] { - (byte)0x80, // signerInfo - (byte)0x01 // Certificate digest with ecdsap256 - }, - management.getAtCertificateDigest() // Hashed8 - ); - } - - // Build the generation time value - byte[] generationTime = ByteHelper.longToByteArray((long)(p_currentTime - 1072915200000L) * 1000L, Long.SIZE / Byte.SIZE); // In microseconds - //TERFactory.getInstance().logDebug("GnPort.buildToBeSignedData: generationTime=" + ByteHelper.byteArrayToString(generationTime)); - byte[] headersField = ByteHelper.concat( - ByteHelper.concat( // SecuredMessage HeaderFields - signerInfo, // signerInfo - new byte[] { - (byte)0x00, // generationTime - }, - generationTime // Time64 value - ) - ); - // Add Its-Aid for Other profile - int itsAid = management.getItsAidOther(); - byte[] b; - if (itsAid < 128) { - b = new byte[] { (byte)itsAid }; - } else { - b = SecurityHelper.getInstance().size2tls(itsAid); - } - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x03 // GenerationLocation - }, - management.getLatitude(), // Latitude - management.getLongitude(), // Longitude - new byte[] { (byte)0x00, (byte)0x00 }, // Elevation - new byte[] { - (byte)0x05 // Its-aid - }, - b - ); - byte[] headersFieldLength = SecurityHelper.getInstance().size2tls(headersField.length); - //TERFactory.getInstance().logDebug("GnPort.buildToBeSignedData: headersField=" + ByteHelper.byteArrayToString(headersField)); - byte[] toBeSignedData = ByteHelper.concat( - new byte[] { // SecuredMessage version - (byte)0x02 // version - }, - headersFieldLength, // HeadersField length - headersField, // HeaderFields - new byte[] { // SecuredMessage Payloads - (byte)0x01, // Secured payload type: signed (1) - (byte)p_beacon.length // Data payload length - }, - p_beacon, // End of SecuredMessage Payloads - new byte[] { (byte)0x43 }, // Signature length - new byte[] { (byte)0x01 } // Signature - ); - //TERFactory.getInstance().logDebug("GnPort.buildToBeSignedData: toBeSignedData=" + ByteHelper.byteArrayToString(toBeSignedData)); - - return toBeSignedData; - } - - private byte[] signSecuredMessage(final byte[] p_toBeSignedData) { - //TERFactory.getInstance().logDebug("GnPort.signSecuredMessage: toBeSignedData: " + ByteHelper.byteArrayToString(p_toBeSignedData)); - - byte[] securedBeaconHeader = null; - // Signed the data - byte[] signatureBytes; - try { - signatureBytes = CryptoLib.signWithEcdsaNistp256WithSha256(p_toBeSignedData, management.getSigningPrivateKey()); - //TERFactory.getInstance().logDebug("GnPort.signSecuredMessage: signatureBytes=" + ByteHelper.byteArrayToString(signatureBytes)); - // Add signature - securedBeaconHeader = ByteHelper.concat( - p_toBeSignedData, - new byte[] { - (byte)0x00, // Public Key Alg: ecdsa nistp256 with sha256 (0) - (byte)0x02 // ECC Point Type: compressed lsb y-0 (2) - }, // Signature header - ByteHelper.extract(signatureBytes, 2, signatureBytes.length - 2) - ); - - - if (management.isEnforceSecuredModeSet()) { - boolean result = CryptoLib.verifyWithEcdsaNistp256WithSha256(p_toBeSignedData, signatureBytes, management.getSigningPublicKeyX(), management.getSigningPublicKeyY()); - //TERFactory.getInstance().logDebug("GnPort.signSecuredMessage: Verify signature: pubX" + ByteHelper.byteArrayToString(management.getSigningPublicKeyX())); - //TERFactory.getInstance().logDebug("GnPort.signSecuredMessage: Verify signature: pubY" + ByteHelper.byteArrayToString(management.getSigningPublicKeyY())); - //TERFactory.getInstance().logDebug("GnPort.signSecuredMessage: Verify signature: " + new Boolean(result));*/ - //TERFactory.getInstance().logDebug("<<< GnPort.signSecuredMessage: sendBeacon: " + ByteHelper.byteArrayToString(securedBeaconHeader)); - return (result) ? securedBeaconHeader : null; - } - return securedBeaconHeader; - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - //TERFactory.getInstance().logDebug(">>> GnPort.send: " + ByteHelper.byteArrayToString(message)); - - HashMap params = new HashMap(); - - byte[] destMacAddress = ByteHelper.extract(message, message.length - 10, 6); - int its_aid = ByteHelper.byteArrayToInt(ByteHelper.extract(message, message.length - 4, 4)); - message = ByteHelper.extract(message, 0, message.length - 10); - params.put(EthernetLayer.LINK_LAYER_DESTINATION, destMacAddress); - if (management.isSecuredModeSet()) { // Secure mode disabled - message = createSecuredMessage(message, its_aid); - } - -// ByteHelper.dump("GnPort.send", message); - return send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> GnPort.receive: " + ByteHelper.byteArrayToString(message)); - - byte[] basicHdr = new byte[4]; - System.arraycopy(message, 0, basicHdr, 0, 4); - int headerType = -1; - int headerSubType = -1; - byte[] sopv = new byte[24]; - if ((basicHdr[0] & 0x0f) == 0x01) { // Common header - Secure mode disabled - byte[] commonHdr = new byte[8]; - System.arraycopy(message, 4, commonHdr, 0, 8); - byte[] htHst = new byte[1]; - System.arraycopy(commonHdr, 1, htHst, 0, 1); - headerType = (int)(htHst[0] >> 4); - headerSubType = (int)(htHst[0] & 0x000000000F); - // Update LPV table - int sopvPos = 12; - if(headerType != HT_BEACON && !(headerType == HT_TSB && headerSubType == HST_SHB) ) { - sopvPos += 4; - } - try { - System.arraycopy(message, sopvPos, sopv, 0, 24); - } - catch (IndexOutOfBoundsException e) { // Decoding issue - return; - } - //TERFactory.getInstance().logDebug("GnPort.receive: sopv=" + ByteHelper.byteArrayToString(sopv)); - // Security disable, null will be translated into omit - lowerInfo.put(SecurityHelper.SEC_SSP, null); - lowerInfo.put(SecurityHelper.SEC_ITS_AID, null); - } else if ((basicHdr[0] & 0x0f) == 0x02) { // Secured tag - byte[] payload = SecurityHelper.getInstance().checkSecuredProfileAndExtractPayload(message, basicHdr.length, management.isEnforceSecuredModeSet(), management.getItsAidOther(), lowerInfo); - if (payload != null) { - //TERFactory.getInstance().logDebug("GnPort.receive: payload=" + ByteHelper.byteArrayToString(payload)); - byte[] commonHdr = new byte[8]; - System.arraycopy(payload, 0, commonHdr, 0, 8); - //TERFactory.getInstance().logDebug("GnPort.receive: commonHdr=" + ByteHelper.byteArrayToString(commonHdr)); - byte[] htHst = new byte[1]; - System.arraycopy(commonHdr, 1, htHst, 0, 1); - headerType = (int)(htHst[0] >> 4); - headerSubType = (int)(htHst[0] & 0x000000000F); - // Update LPV table - int sopvPos = commonHdr.length; - if(headerType != HT_BEACON && !(headerType == HT_TSB && headerSubType == HST_SHB) ) { - sopvPos += 4; - } - System.arraycopy(payload, sopvPos, sopv, 0, 24); - } else { - // Drop it - TERFactory.getInstance().logError("GnPort.receive: Invalid packet"); - return; - } - } else { - // Drop it - TERFactory.getInstance().logError("GnPort.receive: Invalid basic header type"); - return; - } - //TERFactory.getInstance().logDebug("GnPort.receive: sopv=" + ByteHelper.byteArrayToString(sopv)); - - byte[] gn = new byte[8]; - System.arraycopy(sopv, 0, gn, 0, 8); - byte[] mid = new byte[6]; - System.arraycopy(gn, 2, mid, 0, 6); - byte[] tst = new byte[4]; - System.arraycopy(sopv, 8, tst, 0, 4); - management.gnUpdateLocTable(mid, ByteHelper.byteArrayToInt(tst), sopv); - - // Filter beacons - byte [] beaconFilter = management.getGnEnqueueBeacon(); - if(headerType != HT_BEACON || beaconFilter != null) { - if(headerType == HT_BEACON) { - byte[] filterMid = new byte[6]; - System.arraycopy(beaconFilter, 2, filterMid, 0, 6); - if(java.util.Arrays.equals(mid, filterMid) == false) { - // Received beacon does not match filter - return; - } - } - // Encode with GN indication header - // Extract LINK_LAYER_DESTINATION - byte[] msgInd = ByteHelper.concat(message, (byte[])lowerInfo.get(EthernetLayer.LINK_LAYER_DESTINATION)); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#dispose() - */ - @Override - public void dispose() { - if(running && beaconThread != null) { - running = false; - try { - beaconThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - super.dispose(); - } - - private byte[] createSecuredMessage(final byte[] message, int its_aid) { - //TERFactory.getInstance().logDebug(">>> GnPort.createSecuredMessage:" + ByteHelper.byteArrayToString(message)); - - // Extract and update the basicHeader - byte[] basicHdr = ByteHelper.extract(message, 0, 4); - if ((basicHdr[0] & 0x02) == 0x02) { // Message already secured by the TE - return message; - } - // Set nextHeader to secured - basicHdr[0] &= 0xFE; - basicHdr[0] |= 0x02; - //TERFactory.getInstance().logDebug("GnPort.createSecuredMessage: basicHdr=" + ByteHelper.byteArrayToString(basicHdr)); - - // Extract and update the basicHeader - byte[] commonHdr = ByteHelper.extract(message, 4, 8); - //TERFactory.getInstance().logDebug("GnPort.createSecuredMessage: commonHdr=" + ByteHelper.byteArrayToString(commonHdr)); - - // Extract SecuredMessage payload - byte[] securedPayload = ByteHelper.extract(message, 4, message.length - 4); - int payloadLength = securedPayload.length; - - // Build the generation time value - long curtime = System.currentTimeMillis(); - byte[] generationTime = ByteHelper.longToByteArray((long)(curtime - 1072915200000L) * 1000L, Long.SIZE / Byte.SIZE); // In microseconds - // Build the payload to be signed - byte[] headersField = ByteHelper.concat( - ByteHelper.concat( // SecuredMessage HeaderFields - new byte[] { - (byte)0x80, // signerInfo - (byte)0x01 // Certificate digest with ecdsap256 - }, - management.getAtCertificateDigest(), // HashedId8 - new byte[] { - (byte)0x00, // generationTime - }, - generationTime // Time64 value - ) - ); - if (its_aid == 36) { // CAM - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x05, // its-aid - (byte)its_aid // 36 = CAM - } - ); - } else if (its_aid == 37) { // DENM - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x03 // GenerationLocation - }, - management.getLatitude(), // Latitude - management.getLongitude(), // Longitude - new byte[] { (byte)0x00, (byte)0x00 }, // Elevation - new byte[] { - (byte)0x05, // its-aid - (byte)its_aid // 37 = DENM - } - ); - } else { // Add Its-Aid for Other profile - byte[] b; - if (its_aid < 128) { - b = new byte[] { (byte)its_aid }; - } else { - b = SecurityHelper.getInstance().size2tls(its_aid); - } - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x03 // GenerationLocation - }, - management.getLatitude(), // Latitude - management.getLongitude(), // Longitude - new byte[] { (byte)0x00, (byte)0x00 }, // Elevation - new byte[] { - (byte)0x05 // Its-aid - }, - b // Other profile - ); - } - byte[] payloadLengthTls = SecurityHelper.getInstance().size2tls(payloadLength); - byte[] toBeSignedData = ByteHelper.concat( - new byte[] { // SecuredMessage version - (byte)0x02 // version - }, - new byte[] { (byte)headersField.length }, // HeadersField length - headersField, // HeaderFields - new byte[] { // SecuredMessage Payloads - (byte)0x01, // Secured payload type: signed (1) - }, - payloadLengthTls, // Data payload length - securedPayload, - new byte[] { (byte)0x43 }, // Signature length - new byte[] { (byte)0x01 } // Signature - ); - //TERFactory.getInstance().logDebug("GnPort.createSecuredMessage: toBeSignedData=" + ByteHelper.byteArrayToString(toBeSignedData)); - - byte[] toBeSent = null; - try { - // Signed the data - byte[] signatureBytes = CryptoLib.signWithEcdsaNistp256WithSha256(toBeSignedData, management.getSigningPrivateKey()); - //TERFactory.getInstance().logDebug("GnPort.createSecuredMessage: signatureBytes=" + ByteHelper.byteArrayToString(signatureBytes)); - // Add signature - toBeSent = ByteHelper.concat( - basicHdr, - toBeSignedData, - new byte[] { - (byte)0x00, // Public Key Alg: ecdsa nistp256 with sha256 (0) - (byte)0x02 // ECC Point Type: compressed lsb y-0 (2) - }, // Signature header - ByteHelper.extract(signatureBytes, 2, signatureBytes.length - 2) - ); - } catch (Exception e) { - e.printStackTrace(); - } - - //TERFactory.getInstance().logDebug("GnPort.createSecuredMessage: toBeSent=" + ByteHelper.byteArrayToString(toBeSent)); - return toBeSent; - } - - /** - * Indicates whether the port is still active. Setting this field to false will cause - * the beaconing thread to stop its execution. - */ - private volatile boolean running; - - /** - * Beaconing thread instance. - */ - private Thread beaconThread = null; -} - diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/IObservable.java b/javasrc/adapter/org/etsi/its/adapter/ports/IObservable.java deleted file mode 100644 index daa188a8ea704160e7fccd6e456548a421e4c33c..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/IObservable.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Interface for observable objects - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.Observer; - -/** - * Interface for observable objects - */ -public interface IObservable { - - /** - * If this object has changed then notify all of its observers - * @param arg - */ - void notifyObservers(Object arg); - - /** - * Adds an observer to the set of observers for this object, provided that it is not the same as some observer already in the set - * @param observer Observer to be registered - */ - void addObserver(Observer observer); - - /** - * Clears the observer list so that this object no longer has any observers - */ - void deleteObservers(); - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/IPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/IPort.java deleted file mode 100644 index 2a983fbb9be7e957a92322cc333e8aa00efa4960..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/IPort.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Interface to port implementation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -/** - * Interface to port implementation - */ -public interface IPort { - - /** - * Gets the name of the component on which this port instance is mapped - * @return Component's name - */ - String getComponentName(); - - /** - * Gets the name of the port - * @return Port's name - */ - String getPortName(); - - /** - * Sends a message to SUT through the port - * @param message encoded message to be sent - * @return true if send operation is successful, false otherwise - */ - boolean send(byte[] message); - - /** - * Deletes the port instance in a clean manner (stops background threads, ...) - */ - void dispose(); - -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/IicpPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/IicpPort.java deleted file mode 100644 index 0c4159d03f6b59c3d168e7d9af5481bc2fe4f638..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/IicpPort.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.EthernetLayer; -import org.etsi.its.adapter.layers.IEthernetSpecific; -import org.etsi.ttcn.tci.CharstringValue; - -public class IicpPort extends ProtocolPort implements IEthernetSpecific { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public IicpPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IEthernetSpecific#getEthernetType() - */ - @Override - public short getEthernetType() { - - // Retrieve EthernetType value - Integer iutEthernetTypeValue = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("IutEthernetTypeValue")).getString()); - return iutEthernetTypeValue.shortValue(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - // Encode with IicpInd indication header - // Extract LINK_LAYER_DESTINATION - byte[] iicpInd = ByteHelper.concat(message, (byte[])lowerInfo.get(EthernetLayer.LINK_LAYER_DESTINATION)); - super.receive(iicpInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - ByteHelper.dump("IicpPort.send", message); - HashMap params = new HashMap(); - return send(message, params); - } - - public boolean triggerInSapPrimitiveUp(byte[] inSapPrimitiveUp) { - ByteHelper.dump("IicpPort.triggerInSapPrimitiveUp", inSapPrimitiveUp); - HashMap params = new HashMap(); - params.put(EthernetLayer.LINK_LAYER_DESTINATION, management.getLinkLayerAddress()); - return send(inSapPrimitiveUp, params); - } - -} // End of class FntpPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/IvimPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/IvimPort.java deleted file mode 100644 index cfda5dc16a37e19f3bf179bafbe90d6687a2f642..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/IvimPort.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * CAM port implementation - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -/** - * CAM port implementation - */ -public class IvimPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public IvimPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[], java.util.Map) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> IvimPort.receive: " + ByteHelper.byteArrayToString(message)); - - if (message[1] != 0x06) { // Check that received packet has IVIM message id - See ETSI TS 102 894 - TERFactory.getInstance().logDebug("IvimPort.receive: drop packet " + ByteHelper.byteArrayToString(message)); - return; // Drop it - } - - // Encode with CAM indication header - byte[] msgInd = ByteHelper.concat( - message, - new byte[] { (Byte) lowerInfo.get(GnLayer.GN_NEXTHEADER) }, - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_SUBTYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_LIFETIME), Integer.SIZE / Byte.SIZE), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TRAFFICCLASS), 1), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORT), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORTINFO) - ); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - params.put(BtpLayer.BTP_DSTPORT, 2006); - params.put(BtpLayer.BTP_SRCPORT, 500); - params.put(GnLayer.GN_TYPE, GnLayer.HT_GEOBROADCAST); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_MULTIHOP); - params.put(GnLayer.GN_LATITUDE, ByteHelper.byteArrayToLong(management.getLatitude())); - params.put(GnLayer.GN_LONGITUDE, ByteHelper.byteArrayToLong(management.getLongitude())); - params.put(GnLayer.GN_DISTANCEA, 0); - params.put(GnLayer.GN_DISTANCEB, 0); - params.put(GnLayer.GN_ANGLE, 0); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - return send(message, params); - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/MapemSpatemPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/MapemSpatemPort.java deleted file mode 100644 index 1b72ec59fb387cb40db5a19958cc8dd41ec84098..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/MapemSpatemPort.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -public class MapemSpatemPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public MapemSpatemPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[], java.util.Map) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - //TERFactory.getInstance().logDebug(">>> MapemSpatemPort.receive: " + ByteHelper.byteArrayToString(message)); - - if ((message[1] != 0x04) && (message[1] != 0x05)) { // Check that received packet has MAPEM/SPATEM message id - See ETSI TS 102 894 - TERFactory.getInstance().logDebug("MapemSpatemPort.receive: drop packet " + ByteHelper.byteArrayToString(message)); - return; // Drop it - } - - // Encode with MAPEM/SPATEM indication header - byte[] msgInd = ByteHelper.concat( - message, - new byte[] { (Byte) lowerInfo.get(GnLayer.GN_NEXTHEADER) }, - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_SUBTYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_LIFETIME), Integer.SIZE / Byte.SIZE), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TRAFFICCLASS), 1), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORT), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORTINFO) - ); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - if (message[1] == 0x5) { // MAPEM, see ITS-Container - params.put(BtpLayer.BTP_DSTPORT, 2003); - } else if (message[1] == 0x4) { // SPATEM, see ITS-Container - params.put(BtpLayer.BTP_DSTPORT, 2004); - } else { - params.put(BtpLayer.BTP_DSTPORT, 0); - } - params.put(BtpLayer.BTP_SRCPORT, 0); - params.put(GnLayer.GN_TYPE, GnLayer.HT_GEOBROADCAST); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_MULTIHOP); - params.put(GnLayer.GN_LATITUDE, ByteHelper.byteArrayToLong(management.getLatitude())); - params.put(GnLayer.GN_LONGITUDE, ByteHelper.byteArrayToLong(management.getLongitude())); - params.put(GnLayer.GN_DISTANCEA, 0); - params.put(GnLayer.GN_DISTANCEB, 0); - params.put(GnLayer.GN_ANGLE, 0); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - return send(message, params); - } -} // End of class MapSpatPort - diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/PortEvent.java b/javasrc/adapter/org/etsi/its/adapter/ports/PortEvent.java deleted file mode 100644 index 089ae7aeeba94e1ac33d45ec198bc395c94784e7..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/PortEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Event transmitted by ports as observable objects to observers - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -/** - * Event transmitted by ports as observable objects to observers - */ -public class PortEvent { - - /** - * Byte data to transmit - */ - private byte[] _message; - - /** - * Name of the port - */ - private String _portName; - - /** - * Name of the component owner; needed for enqueueing message - */ - private String _componentName; - - /** - * Constructor - * @param message Data to be transmitted - * @param receptionTime Message reception time - * @param portName Name of the port - * @param componentName Name of the component owning the port instance - */ - public PortEvent(final byte[] message, String portName, String componentName) { - _message = message; - _portName = portName; - _componentName = componentName; - } - - /** - * Gets the data buffer - * @return Data as a byte array - */ - public byte[] get_message() { - return _message; - } - - /** - * Gets the port name - * @return Name of the port - */ - public String getPortName() { - return _portName; - } - - /** - * Gets the component name - * @return Name of the component - */ - public String getComponentName() { - return _componentName; - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPort.java deleted file mode 100644 index e88983c312892fe7275068b199e236e6e16c0555..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPort.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Abstract class for Protocol-related port implementations - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; -import java.util.Observable; -import java.util.Observer; -import java.util.Stack; - -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.Management; -import org.etsi.its.adapter.layers.Layer; - -/** - * Abstract class for Protocol-related port implementations - */ -public abstract class ProtocolPort extends Layer implements IPort, IObservable { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public ProtocolPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(Management.getInstance(componentName), parseStackDesc(lowerStackDesc)); - this.portName = portName; - this.componentName = componentName; - Management.getInstance(componentName).setLinkLayerAddress(ByteHelper.hexStringToByteArray(linkLayerAddress)); - initialize(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#getPortName() - */ - @Override - public String getPortName() { - return portName; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#getComponentName() - */ - @Override - public String getComponentName() { - return componentName; - } - - /** - * Parses a stack description in the form "Layer/Layer/Layer/..." - * @param lowerStackDesc String representing a stack description - * @return Parsed stack description - */ - private static Stack parseStackDesc(String lowerStackDesc) { - Stack lowerStack = new Stack(); - String [] layers = lowerStackDesc.split("/"); - for(int i=layers.length-1; i >=0; i--) { - if(!layers[i].equalsIgnoreCase("")) { - lowerStack.push(layers[i]); - } - } - return lowerStack; - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - HashMap params = new HashMap(); - -// ByteHelper.dump("ProtocolPortLayer.send", message); - return send(message, params); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#receive(byte[]) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { - setChanged(); - notifyObservers(new PortEvent(message, portName, componentName)); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#dispose() - */ - @Override - public void dispose() { - unregister(null); - } - - /** - * Marks this Observable object as having been changed - */ - protected void setChanged() { - observable.setChanged(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#notifyObservers(java.lang.Object) - */ - @Override - public void notifyObservers(Object arg) { - observable.notifyObservers(arg); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#addObserver(java.util.Observer) - */ - @Override - public void addObserver(Observer observer) { - observable.addObserver(observer); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IObservable#deleteObservers() - */ - @Override - public void deleteObservers() { - observable.deleteObservers(); - } - - /** - * Embedded object for implementing Observable behaviour - */ - private ObservablePort observable = new ObservablePort(); - - /** - * Name of the port - */ - private String portName; - - /** - * Name of the component owner; needed for enqueueing message - */ - private String componentName; - - /** - * Nested class for implementing Observable behaviour - */ - private class ObservablePort extends Observable implements IObservable { - - /* (non-Javadoc) - * @see java.util.Observable#setChanged() - */ - @Override - public void setChanged() { - super.setChanged(); - } - } -} diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPortFactory.java b/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPortFactory.java deleted file mode 100644 index bb2cc5b7d6a28894f104169894c8f269c4ea7d5e..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/ProtocolPortFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Protocol port factory (Singleton) - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.lang.reflect.Constructor; -import java.util.Map; -import java.util.TreeMap; - -import org.etsi.adapter.TERFactory; - -/** - * Protocol port factory (Singleton) - */ -public class ProtocolPortFactory { - - /** - * Unique instance of the factory - */ - private static ProtocolPortFactory instance = new ProtocolPortFactory(); - - /** - * List of the registered protocol port types - */ - protected Map> ports = new TreeMap>(); - - /** - * Private constructor (Singleton pattern) - */ - private ProtocolPortFactory() { - // Register the ports - Refer to TTCN-3 component LibIts_TestSystem.ItsSystem for ports name - ports.put("camPort", CamPort.class); - ports.put("denmPort", DenmPort.class); - ports.put("mapemSpatemPort", MapemSpatemPort.class); - ports.put("ivimPort", IvimPort.class); - ports.put("sremSsemPort", SremSsemPort.class); - ports.put("btpPort", BtpPort.class); - ports.put("geoNetworkingPort", GnPort.class); - ports.put("ipv6OverGeoNetworkingPort", Gn6Port.class); - try { - ports.put("v2gPort", Class.forName( "org.etsi.its.adapter.ports.V2GPort" ).asSubclass(ProtocolPort.class)); - } catch( ClassNotFoundException e ) {} - } - - /** - * Gets the unique factory instance - * @return ProtocolPortFactory instance - */ - public static ProtocolPortFactory getInstance(){ - return instance; - } - - /** - * Creates a port of the desired type - * @param portName Name of the port - * @param componentName Name of the component owning the port instance - * @param lowerStackDesc Description of the lower protocol stack of the port in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - * @return Protocol port instance - */ - public ProtocolPort createPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - //TERFactory.getInstance().logDebug(">>> ProtocolPortFactory.createPort: " + portName + ", " + componentName + ", " + lowerStackDesc + ", " + linkLayerAddress); - - ProtocolPort port = null; - Class[] ctorParams = {portName.getClass(), componentName.getClass(), lowerStackDesc.getClass(), linkLayerAddress.getClass()}; - - try { - Class cls = ports.get(portName); - - if (cls == null) { - throw new RuntimeException("No class registered under " + portName); - } - - Constructor ctor = cls.getConstructor(ctorParams); - port = ctor.newInstance(portName, componentName, lowerStackDesc, linkLayerAddress); - } catch (Exception ex) { - ex.printStackTrace(); - } - - return port; - } -} - \ No newline at end of file diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/SremSsemPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/SremSsemPort.java deleted file mode 100644 index 3f1db373c4b767f71daa24e7c59940257e6b81c7..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/SremSsemPort.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.etsi.its.adapter.ports; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.its.adapter.layers.BtpLayer; -import org.etsi.its.adapter.layers.GnLayer; - -public class SremSsemPort extends ProtocolPort { - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public SremSsemPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#receive(byte[], java.util.Map) - */ - @Override - public void receive(byte[] message, Map lowerInfo) { -// TERFactory.getInstance().logDebug(">>> SremSsemPort.receive: " + ByteHelper.byteArrayToString(message)); - - if ((message[1] != 0x09) && (message[1] != 0x0A)) { // Check that received packet has SREM/SSEM message id - See ETSI TS 102 894 - TERFactory.getInstance().logDebug("SremSsemPort.receive: drop packet " + ByteHelper.byteArrayToString(message)); - return; // Drop it - } - - // Encode with SREM/SSEM indication header - byte[] msgInd = ByteHelper.concat( - message, - new byte[] { (Byte) lowerInfo.get(GnLayer.GN_NEXTHEADER) }, - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_SUBTYPE), 1), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_LIFETIME), Integer.SIZE / Byte.SIZE), - ByteHelper.intToByteArray((Integer) lowerInfo.get(GnLayer.GN_TRAFFICCLASS), 1), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORT), - (byte[]) lowerInfo.get(BtpLayer.BTP_DSTPORTINFO) - ); - // Add security info to pass to the ATS - if (lowerInfo.get(SecurityHelper.SEC_SSP) == null) { - byte[] buf = new byte[32]; - msgInd = ByteHelper.concat(msgInd, buf); - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_SSP)); - } - if (lowerInfo.get(SecurityHelper.SEC_ITS_AID) == null) { // It shall not be possible to have SSP absent and ATS_AID present but... - msgInd = ByteHelper.concat(msgInd, new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }); - - } else { - msgInd = ByteHelper.concat(msgInd, (byte[])lowerInfo.get(SecurityHelper.SEC_ITS_AID)); - } - super.receive(msgInd, lowerInfo); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.IPort#send(byte[]) - */ - @Override - public boolean send(byte[] message) { - - HashMap params = new HashMap(); - params.put(BtpLayer.BTP_TYPE, BtpLayer.TYPE_B); - if (message[1] == 0x9) { // SREM, see ITS-Container - params.put(BtpLayer.BTP_DSTPORT, 2007); - } else if (message[1] == 0xa) { // SSEM, see ITS-Container - params.put(BtpLayer.BTP_DSTPORT, 2008); - } else { - params.put(BtpLayer.BTP_DSTPORT, 0); - } - params.put(BtpLayer.BTP_SRCPORT, 0); - params.put(GnLayer.GN_TYPE, GnLayer.HT_TSB); - params.put(GnLayer.GN_SUBTYPE, GnLayer.HST_MULTIHOP); - params.put(GnLayer.GN_LATITUDE, ByteHelper.byteArrayToLong(management.getLatitude())); - params.put(GnLayer.GN_LONGITUDE, ByteHelper.byteArrayToLong(management.getLongitude())); - params.put(GnLayer.GN_NEXTHEADER, "BTP-B"); - return send(message, params); - } -} // End of class MapSpatPort - diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/UpperTesterPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/UpperTesterPort.java deleted file mode 100644 index ee0f8ed88dc2585cb094c43b849435e24aa22863..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/UpperTesterPort.java +++ /dev/null @@ -1,641 +0,0 @@ -/** - * Upper Tester port implementation. This port is used to trigger IUT's upper interface - * - * @author ETSI / STF424 - * @version $URL$ - * $Id$ - * - */ -package org.etsi.its.adapter.ports; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.etsi.adapter.TERFactory; -import org.etsi.certificates.CertificatesIOFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.SecurityHelper; -import org.etsi.ttcn.tci.CharstringValue; - -import de.fraunhofer.sit.c2x.CryptoLib; - -/** This class implements behaviour for Upper Tester port - * The Upper tester entity in the SUT enables triggering Protocol functionalities by simulating primitives from - * application or LDM entities - * It is required to trigger the Protocol layer in the SUT to send Protocol specific messages, which are - * resulting from upper layer primitives - */ -public class UpperTesterPort extends AdapterPort implements IPort, IObservable { - - private static final String SETTINGS_PATTERN = "(\\S+)\\:(\\d+)"; - - private static final String CertificateId = "CERT_UT"; - - /** - * Secured mode status - */ - private String _utSecuredMode = null; - - /** - * Secured root path to access certificates & private keys - */ - private String _utSecuredRootPath = null; - - /** - * Secured configuration identifier - */ - private String _utSecuredConfiId = null; - - /** - * Secured mode status - */ - private boolean _isSecuredMode = false; - - private ByteArrayOutputStream _certificate; - - private ByteArrayOutputStream _hashedId8; - - private ByteArrayOutputStream _signingPrivateKey; - - private String _offlineMode = ""; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param localPortNumber Local port number for the UDP listener - * @param remotePortNumber UDP port listener of remote UT application - */ - public UpperTesterPort(final String portName, final String componentName) { - super(portName, componentName); - - // UDP connection parameters - _utSecuredMode = ((CharstringValue)TERFactory.getInstance().getTaParameter("UtSecuredMode")).getString(); - _utSecuredRootPath = ((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredRootPath")).getString(); - _utSecuredConfiId = ((CharstringValue)TERFactory.getInstance().getTaParameter("TsSecuredConfiId")).getString(); - _offlineMode = ((CharstringValue)TERFactory.getInstance().getTaParameter("OfflineMode")).getString().toLowerCase(); - String settings = ((CharstringValue)TERFactory.getInstance().getTaParameter("UpperTesterSettings")).getString(); - Matcher matcher = settingsPattern.matcher(settings); - if (matcher.find()) { - try { - utPeerAddress = InetAddress.getByName(matcher.group(1)); - } catch (UnknownHostException e1) { - e1.printStackTrace(); - } - utPeerPort = Integer.parseInt(matcher.group(2)); - } else { - // FIXME - } - - if ((_utSecuredMode != null) && _utSecuredMode.equals("true")) { - // Load certificate - _certificate = new ByteArrayOutputStream(); - CertificatesIOFactory.getInstance().loadCertificates(_utSecuredRootPath, _utSecuredConfiId); - if (CertificatesIOFactory.getInstance().readCertificate(CertificateId, _certificate)) { -// TERFactory.getInstance().logDebug("UpperTesterPort.UpperTesterPort: _certificate=" + ByteHelper.byteArrayToString(_certificate.toByteArray())); - _hashedId8 = new ByteArrayOutputStream(); - _signingPrivateKey = new ByteArrayOutputStream(); - CertificatesIOFactory.getInstance().readCertificateDigest(CertificateId, _hashedId8); -// TERFactory.getInstance().logDebug("UpperTesterPort.UpperTesterPort: _hashedId8=" + ByteHelper.byteArrayToString(_hashedId8.toByteArray())); - CertificatesIOFactory.getInstance().readSigningKey(CertificateId, _signingPrivateKey); -// TERFactory.getInstance().logDebug("UpperTesterPort.UpperTesterPort: _signingPrivateKey=" + ByteHelper.byteArrayToString(_signingPrivateKey.toByteArray())); - - _isSecuredMode = true; - } - } - - // UDP socket for communication with UT - running = true; - try { - utSocket = new DatagramSocket(/*utPeerPort*/); - utThread = new UdpThread(utSocket); - utThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public boolean send(final byte[] message) { - if (true /*or _offlineMode.equals("true")*/) { /* FIXME: For debug only. Uncomment if no UT - Do not forget the return true below*/ - try { - Thread.sleep(500); - } catch (InterruptedException e) { - // Do nothing, we do not care - } - - setChanged(); - byte[] rsp; - switch (message[0]) { - case (byte)0x00: - rsp = new byte[]{(byte)0x01, (byte)0x01}; - break; - case (byte)0x02: // UtChangePosition - rsp = new byte[]{(byte)0x03, (byte)0x01}; - break; - case (byte)0x04: // UtChangePseudonym - rsp = new byte[]{(byte)0x05, (byte)0x01}; - break; - case (byte)0x06: // UtActivatePositionTime - rsp = new byte[]{(byte)0x07, (byte)0x01}; - break; - case (byte)0x08: // UtDeactivatePositionTime - rsp = new byte[]{(byte)0x09, (byte)0x01}; - break; - case (byte)0x10: // UtDenmTrigger - rsp = ByteHelper.concat( - new byte[]{ (byte)0x11, (byte)0x01 }, - new byte[] { (byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA }, // StationID - new byte[] { (byte)0x01, (byte)0xFF } // SequenceNumber - ); - break; - case (byte)0x12: // UtDenmUpdate - rsp = ByteHelper.concat( - new byte[]{ (byte)0x13, (byte)0x01 }, - new byte[] { (byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA }, // StationID - new byte[] { (byte)0x01, (byte)0xFF } // SequenceNumber - ); - break; - case (byte)0x14: // UtDenmTermination - rsp = new byte[]{(byte)0x15, (byte)0x01}; - break; - //reserved(0x92), - case (byte)0x93: // UtSec_setCertificate - case (byte)0x94: // UtSec_setPrivateKey - case (byte)0x95: // UtSec_setTrustPoint( - rsp = new byte[]{(byte)0x91, (byte)0x01}; // UtSecResult - break; - case (byte)0xA0: // UtMapemSpatemTrigger - rsp = new byte[]{(byte)0xA1, (byte)0x01}; // UtMapemSpatemTriggerResult - break; - case (byte)0xA4: // UtIvimTrigger - rsp = new byte[]{(byte)0xA5, (byte)0x01, (byte)0xA0, (byte)0xA0}; // UtIvimTriggerResult - break; - case (byte)0xA6: // UtIvimUpdate - rsp = new byte[]{(byte)0xA7, (byte)0x01, (byte)0xA0, (byte)0xA0}; // UtIvimUpdateResult - break; - case (byte)0xA8: // UtIvimTermination - rsp = new byte[]{(byte)0xA9, (byte)0x01, (byte)0xA0, (byte)0xA0}; // UtIvimTerminationResult - break; - case (byte)0xAB: // UtSremTrigger - rsp = new byte[]{(byte)0xAC, (byte)0x01}; // UtSremTriggerResult - break; - case (byte)0xAD: // UtSremUpdate - rsp = new byte[]{(byte)0xAE, (byte)0x01}; // UtSremUpdateResult - break; - default: - if ((message[0] >= (byte)0x30) && (message[0] <= (byte)0x3F)) { // UtCamTrigger_xxx - rsp = new byte[]{(byte)0x21, (byte)0x00}; // UtCamTriggerResult - } else { - rsp = new byte[]{(byte)0x24, (byte)0x00}; - } - break; - } - notifyObservers(new PortEvent(rsp, getPortName(), getComponentName())); - } -/* FIXME: For debug only */if(true) - return true; -/**/ - try { - ByteArrayOutputStream dataToSent = new ByteArrayOutputStream(); - dataToSent.write(message); - if (_isSecuredMode) { // Send a secured message - // Build the secured message - ByteArrayOutputStream toBeSignedData = new ByteArrayOutputStream(); - buildToBeSignedData(dataToSent, toBeSignedData); - // Sign data - dataToSent = new ByteArrayOutputStream(); - signSecuredMessage(toBeSignedData, dataToSent); - } - byte[] output = dataToSent.toByteArray(); - DatagramPacket packet = new DatagramPacket(output, output.length, utPeerAddress, utPeerPort); - utSocket.send(packet); - - return true; - } catch (Exception e) { - e.printStackTrace(); - } - - return false; - } - - @Override - public void dispose() { - if(running) { - running = false; - if(utThread != null) { - try { - utSocket.close(); - utThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - - private DatagramSocket utSocket; - private Thread utThread; - private InetAddress utPeerAddress = null; - private int utPeerPort = 0; - private Pattern settingsPattern = Pattern.compile(SETTINGS_PATTERN); - - /** - * Indicates whether the port is still active. Setting this field to false will cause - * the UDP communication with Upper Tester to be stopped - */ - private volatile boolean running; - - private class UdpThread extends Thread { - - private DatagramSocket taSocket; - - public UdpThread(DatagramSocket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - - while(running) { - try { - byte[] buf = new byte[4096]; - - // receive packet - DatagramPacket packet = new DatagramPacket(buf, buf.length); - taSocket.receive(packet); - - if (_isSecuredMode) { // Secure mode enabled - byte[] message = ByteHelper.extract(packet.getData(), packet.getOffset(), packet.getLength()); - byte[] payload = checkSecuredOtherProfileAndExtractPayload(message); - - if (payload != null) { // Notify received payload - setChanged(); - notifyObservers(new PortEvent(payload, getPortName(), getComponentName())); - } // else, packet was dropped - } else { // Notify received payload - setChanged(); - notifyObservers(new PortEvent(ByteHelper.extract(packet.getData(), packet.getOffset(), packet.getLength()), getPortName(), getComponentName())); - } - } catch (IOException e) { - running = false; - } - } - taSocket.close(); - } - - } // End of class UdpThread - - private byte[] checkSecuredOtherProfileAndExtractPayload(final byte[] p_message) { - TERFactory.getInstance().logDebug(">>> UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: " + ByteHelper.byteArrayToString(p_message)); - ByteHelper.dump("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: ", p_message); - - ByteArrayInputStream decvalue = new ByteArrayInputStream(p_message); - - // Check version - if (decvalue.read() != 2) { - // Drop it - TERFactory.getInstance().logError("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Drop packet - Wrong version number"); - return null; - } - // Extract header fields length and header fields - long headerFieldsLength = SecurityHelper.getInstance().tls2size(decvalue); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: headerFieldsLength:" + headerFieldsLength); - byte[] headerFields = new byte[(int) headerFieldsLength]; - decvalue.read(headerFields, 0, (int) headerFieldsLength); - ByteArrayOutputStream certificateKeys = new ByteArrayOutputStream(); - if (!checkHeaderfields(headerFields, certificateKeys)) { - // Drop it - TERFactory.getInstance().logError("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Drop packet - Wrong Headerfields"); - return null; - } - byte[] aaSigningPublicKeyX, aaSigningPublicKeyY; - aaSigningPublicKeyX = ByteHelper.extract(certificateKeys.toByteArray(), 0, 32); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - aaSigningPublicKeyY = ByteHelper.extract(certificateKeys.toByteArray(), 32, 32); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: headerFields:" + ByteHelper.byteArrayToString(headerFields)); - // Extract payload, decvalue is updated with the payload - if (decvalue.read() != 1) { - // Drop it - TERFactory.getInstance().logError("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Drop packet - Wrong Payload type"); - return null; - } - long payloadLength = SecurityHelper.getInstance().tls2size(decvalue); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: payloadLength:" + payloadLength); - byte[] payload = new byte[(int) payloadLength]; - decvalue.read(payload, 0, (int) payloadLength); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: payload:" + ByteHelper.byteArrayToString(payload)); - // Extract Secure Trailer - long secureTrailerLength = SecurityHelper.getInstance().tls2size(decvalue); - byte[] secureTrailer = new byte[(int) secureTrailerLength]; - decvalue.read(secureTrailer, 0, secureTrailer.length); - ByteArrayOutputStream signature = new ByteArrayOutputStream(); - if (!extractMessageSignature(secureTrailer, signature)) { - // Drop it - TERFactory.getInstance().logError("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Drop packet - Wrong Signatures"); - return null; - } - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: signature:" + ByteHelper.byteArrayToString(signature.toByteArray())); - // Build signed data - byte[] toBeVerifiedData = ByteHelper.extract( - p_message, - 0, - p_message.length - (int)(secureTrailerLength - 1 /* Exclude signature structure but keep signature type and signature length */) - ); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload:" + ByteHelper.byteArrayToString(toBeVerifiedData)); - // Calculate Digest digest from the buffer toBeVerifiedData - boolean result; - try { - result = CryptoLib.verifyWithEcdsaNistp256WithSha256( - toBeVerifiedData, - signature.toByteArray(), - aaSigningPublicKeyX, - aaSigningPublicKeyY - ); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Verify signature: " + new Boolean(result)); - if (!result) { - // Drop packet - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: toBeVerifiedData :" + ByteHelper.byteArrayToString(toBeVerifiedData)); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: signature :" + ByteHelper.byteArrayToString(signature.toByteArray())); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - TERFactory.getInstance().logDebug("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: aaSigningPublicKeyY:" + ByteHelper.byteArrayToString(aaSigningPublicKeyY)); - TERFactory.getInstance().logError("UpperTesterPort.checkSecuredOtherProfileAndExtractPayload: Drop packet - Invalid signature"); - return null; - } - - return payload; - } catch (Exception e) { - e.printStackTrace(); - } - - // Drop packet - return null; - } - - private boolean checkHeaderfields(byte[] p_headerfields, final ByteArrayOutputStream p_keys) { // TODO Common with GnLayer and UpperTester, to be grouped - TERFactory.getInstance().logDebug(">>> UpperTesterPort.checkHeaderfields: " + ByteHelper.byteArrayToString(p_headerfields)); - - // Sanity check - if (p_headerfields.length == 0) { - return false; - } - // Extract digest or certificate - int signerInfoTypeIndex = 0; - if ( - ((p_headerfields[signerInfoTypeIndex++] & 0x80) != 0x80) || // SignerInfo Type: certificate digest with ecdsap256 (1) - (p_headerfields[signerInfoTypeIndex++] != 0x02) // SignerInfo Type: certificate (2) - ) { - // Drop it - TERFactory.getInstance().logError("UpperTesterPort.checkHeaderfields: Drop packet - Certificate"); - return false; - } - // Extract certificate because of it is an Other message profile - byte[] certificate = decodeCertificate(p_headerfields, signerInfoTypeIndex, p_keys); - signerInfoTypeIndex += certificate.length; - TERFactory.getInstance().logDebug("UpperTesterPort.checkHeaderfields: Certificate:" + ByteHelper.byteArrayToString(certificate)); - // TODO check other fields - - return true; - } - - private byte[] decodeCertificate(final byte[] p_headerfields, final int p_offset, final ByteArrayOutputStream p_keys) { // TODO Common with GnLayer and UpperTester, to be grouped - TERFactory.getInstance().logDebug("UpperTesterPort.decodeCertificate"); - - ByteArrayInputStream headerfields = new ByteArrayInputStream(p_headerfields, p_offset, p_headerfields.length - p_offset); - ByteArrayOutputStream cert = new ByteArrayOutputStream(); // FIXME To be removed - try { - // Version - cert.write((byte)headerfields.read()); - if (cert.toByteArray()[0] != 0x02) { - TERFactory.getInstance().logDebug("UpperTesterPort.decodeCertificate: Wrong version number"); - return null; - } - // SignerInfo type - byte signerInfoType = (byte)headerfields.read(); - cert.write(signerInfoType); - switch (signerInfoType) { - case 0x01: - byte[] digest = new byte[8]; - headerfields.read(digest, 0, digest.length); - cert.write(digest); - break; - // FIXME To be continued - } // End of 'switch' statement - // SubjectInfo type - byte subjectInfoType = (byte)headerfields.read(); - cert.write(subjectInfoType); - long length = SecurityHelper.getInstance().tls2size(headerfields); - if (length != 0) { - // FIXME To be continued - } else { - cert.write(0x00); - } - // Subject Attributes length - length = SecurityHelper.getInstance().tls2size(headerfields); - byte[] b = SecurityHelper.getInstance().size2tls((int) length); - cert.write(b); - // Subject Attributes - b = new byte[(int) length]; - headerfields.read(b, 0, b.length); - cert.write(b); - int offset = 0; - if (b[offset++] == 0x00) { // Subject Attribute: verification key (0) - if (b[offset++] == 0x00) { // Public Key Alg: ecdsa nistp256 with sha256 (0) - if (b[offset++] == 0x04) { // ECC Point Type: uncompressed (4) - p_keys.write(b, offset, 32); - offset += 32; - p_keys.write(b, offset, 32); - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - // Validity Restriction - length = SecurityHelper.getInstance().tls2size(headerfields); - if (length != 0) { - b = SecurityHelper.getInstance().size2tls((int) length); - cert.write(b); - b = new byte[(int) length]; - headerfields.read(b, 0, b.length); - cert.write(b); - } else { - cert.write((byte)0x00); - } // TODO Process Validity Restriction -// // Geographical region -// length = SecurityHelper.getInstance().tls2size(buf); -// if (length != 0) { -// b = SecurityHelper.getInstance().size2tls((int) length); -// cert.write(b); -// b = new byte[(int) length]; -// buf.read(b, 0, b.length); -// cert.write(b); -// } else { -// cert.write((byte)0x00); -// } // TODO Process Geographical region - // Signature - byte publicKeyAlg = (byte)headerfields.read(); - cert.write(publicKeyAlg); - switch (publicKeyAlg) { - case 0x00: // ecdsa nistp256 with sha256 - byte eccPointType = (byte)headerfields.read(); - cert.write(eccPointType); - switch (eccPointType) { - case 0x00: // ECC Point Type: x-coordinate only - byte[] key = new byte[64]; - headerfields.read(key, 0, key.length); - cert.write(key); - break; - } // End of 'switch' statement - break; - } // End of 'switch' statement - // TODO Check certificate signature - - return cert.toByteArray(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - TERFactory.getInstance().logDebug("UpperTesterPort.decodeCertificate: Unsupported certificate"); - return null; - } - - private boolean extractMessageSignature(final byte[] p_secureTrailer, final ByteArrayOutputStream p_signature) { // TODO Common with GnLayer and UpperTester, to be grouped - TERFactory.getInstance().logDebug(">>> UpperTesterPort.extractMessageSignature: " + ByteHelper.byteArrayToString(p_secureTrailer)); - - // Sanity check - if (p_secureTrailer.length == 0) { - return false; - } - - // Extract digest or certificate - int secureTrailerIndex = 0; - if (p_secureTrailer[secureTrailerIndex++] == 0x01) { // Trailer Type: signature (1) - if (p_secureTrailer[secureTrailerIndex++] == 0x00) { // Public Key Alg: ecdsa nistp256 with sha256 (0) - if (p_secureTrailer[secureTrailerIndex++] == 0x02) { // ECC Point Type: compressed lsb y-0 (2) - if (p_secureTrailer.length == (3 + 2 * 32)) { - // Build the signature vector - try { - p_signature.write(new byte[] { (byte)0x00, (byte)0x00 }); - p_signature.write(ByteHelper.extract(p_secureTrailer, 3, 64)); - - TERFactory.getInstance().logDebug("UpperTesterPort.extractMessageSignature: true"); - return true; - } catch (IOException e) { - e.printStackTrace(); - } - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - } // FIXME To be continued - - // Else, drop it - TERFactory.getInstance().logError("UpperTesterPort.extractMessageSignature: Drop packet - Wrong signature"); - return false; - } - - private void buildToBeSignedData(final ByteArrayOutputStream p_securedData, final ByteArrayOutputStream p_toBeSignedData) throws IOException { - - // Build the SignerInfo field - byte[] signerInfo = null; - signerInfo = ByteHelper.concat( - new byte[] { - (byte)0x80, // signerInfo - (byte)0x02 // Certificate - }, - _certificate.toByteArray() // Certificate value - ); - - // For debug purpose Extract signature from secured 'Other message' - byte[] aaSigningPublicKeyX = ByteHelper.extract( - _certificate.toByteArray(), - 16, // Set position at the beginning of the public keys - 32 - ); -// TERFactory.getInstance().logDebug("UpperTesterPort.DispatchMessage: aaSigningPublicKeyX:" + ByteHelper.byteArrayToString(aaSigningPublicKeyX)); - byte[] aaSigningPublicKeyY = ByteHelper.extract( - _certificate.toByteArray(), - 16 + 32, - 32 - ); -// TERFactory.getInstance().logDebug("UpperTesterPort.DispatchMessage: aaSigningPublicKeyY:" + ByteHelper.byteArrayToString(aaSigningPublicKeyY)); - - // Build the generation time value - byte[] generationTime = ByteHelper.longToByteArray( - System.currentTimeMillis(), - Long.SIZE / Byte.SIZE - ); // In microseconds -// TERFactory.getInstance().logDebug("UpperTesterPort.buildToBeSignedData: generationTime=" + ByteHelper.byteArrayToString(generationTime)); - byte[] headersField = ByteHelper.concat( - ByteHelper.concat( // SecuredMessage HeaderFields - signerInfo, // signerInfo - new byte[] { - (byte)0x00, // generationTime - }, - generationTime // Time64 value - ) - ); - // Add Its-Aid for Other profile - int itsAid = 0x38; // FIXME To be refined - byte[] b; - if (itsAid < 128) { - b = new byte[] { (byte)itsAid }; - } else { - b = SecurityHelper.getInstance().size2tls(itsAid); - } - headersField = ByteHelper.concat( - headersField, - new byte[] { - (byte)0x05 // Its-aid - }, - b - ); - byte[] headersFieldLength = SecurityHelper.getInstance().size2tls(headersField.length); -// TERFactory.getInstance().logDebug("UpperTesterPort.buildToBeSignedData: headersField=" + ByteHelper.byteArrayToString(headersField)); - byte[] payload = p_securedData.toByteArray(); - byte[] toBeSignedData = ByteHelper.concat( - new byte[] { // SecuredMessage version - (byte)0x02 // version - }, - headersFieldLength, // HeadersField length - headersField, // HeaderFields - new byte[] { // SecuredMessage Payloads - (byte)0x01, // Secured payload type: signed (1) - (byte)payload.length // Data payload length - }, - payload, // End of SecuredMessage Payloads - new byte[] { (byte)0x43 }, // Signature length - new byte[] { (byte)0x01 } // Signature - ); -// TERFactory.getInstance().logDebug("UpperTesterPort.buildToBeSignedData: toBeSignedData=" + ByteHelper.byteArrayToString(toBeSignedData)); - - p_toBeSignedData.write(toBeSignedData); - } - - private void signSecuredMessage(final ByteArrayOutputStream p_toBeSignedData, final ByteArrayOutputStream p_securedMessage) throws Exception { -// TERFactory.getInstance().logDebug("UpperTesterPort.signSecuredMessage: toBeSignedData: " + ByteHelper.byteArrayToString(p_toBeSignedData.toByteArray())); - byte[] securedBeaconHeader = null; - // Signed the data - byte[] signatureBytes = CryptoLib.signWithEcdsaNistp256WithSha256(p_toBeSignedData.toByteArray(), new BigInteger(_signingPrivateKey.toByteArray())); -// TERFactory.getInstance().logDebug("UpperTesterPort.signSecuredMessage: signatureBytes=" + ByteHelper.byteArrayToString(signatureBytes)); - // Add signature - securedBeaconHeader = ByteHelper.concat( - p_toBeSignedData.toByteArray(), - new byte[] { - (byte)0x00, // Public Key Alg: ecdsa nistp256 with sha256 (0) - (byte)0x02 // ECC Point Type: compressed lsb y-0 (2) - }, // Signature header - ByteHelper.extract(signatureBytes, 2, signatureBytes.length - 2) - ); - p_securedMessage.write(securedBeaconHeader); -// TERFactory.getInstance().logDebug("<<< UpperTesterPort.signSecuredMessage: sendBeacon: " + ByteHelper.byteArrayToString(p_securedMessage.toByteArray())); - } - -} // End of class UpperTesterPort diff --git a/javasrc/adapter/org/etsi/its/adapter/ports/V2GPort.java b/javasrc/adapter/org/etsi/its/adapter/ports/V2GPort.java deleted file mode 100644 index dd16d3740b736ad7b81e4141affe8fb22ab7ae3b..0000000000000000000000000000000000000000 --- a/javasrc/adapter/org/etsi/its/adapter/ports/V2GPort.java +++ /dev/null @@ -1,326 +0,0 @@ -/** - * V2G port implementation (background thread) - * - * @author ETSI / STFS46 - * @version $URL: $ - * $Id: $ - * - */ -package org.etsi.its.adapter.ports; - -import java.io.IOException; -import java.io.InputStream; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.MulticastSocket; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.adapter.layers.Layer; -import org.etsi.ttcn.codec.its.v2g.ExiHelper; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.IntegerValue; - -/** - * V2G port implementation (background threads) - */ -public class V2GPort extends ProtocolPort { - - private static final byte V2G_IND = 0x01; - private static final byte APP_PROTO_IND = 0x02; - private static final byte SDP_IND = 0x03; - - private String role; - private DatagramSocket sdpSocket; - private Socket v2gSocket = null; - private Thread sdpThread, v2gThread, v2gServerThread; - private InetAddress sdpPeerAddress = null; - private int sdpPeerPort = 15118; - private int v2gPort; - private String v2gHost; - private int v2gtpSentCount = 0; - private int v2gtpReceivedCount = 0; - private byte v2gtpInd = APP_PROTO_IND; - - private ServerSocket v2gServerSocket = null; - - /** - * Indicates whether the port is still active. Setting this field to false will cause - * the beaconing thread to stop its execution. - */ - private volatile boolean running; - - /** - * Constructor - * @param portName Name of the port - * @param componentName Name of the component owning this port instance - * @param lowerStackDesc Description of the port's lower stack in the form "Layer/Layer/Layer/..." - * @param linkLayerAddress Link-layer address to be used by this port as source address (null if not applicable) - */ - public V2GPort(String portName, String componentName, String lowerStackDesc, String linkLayerAddress) { - super(portName, componentName, lowerStackDesc, linkLayerAddress); - - // Initialize state variables - v2gtpSentCount = 0; - v2gtpReceivedCount = 0; - v2gtpInd = APP_PROTO_IND; - ExiHelper.setSchemaId("handshake"); - - role = ((CharstringValue)TERFactory.getInstance().getTaParameter("V2gTsRole")).getString(); - v2gHost = ((CharstringValue)TERFactory.getInstance().getTaParameter("V2gSeccAddress")).getString(); - //v2gPort = Integer.decode(((CharstringValue)TERFactory.getInstance().getTaParameter("V2gSeccPort")).getString()); - v2gPort = ((IntegerValue)TERFactory.getInstance().getTaParameter("V2gSeccPort")).getInt(); - try { - sdpPeerAddress = InetAddress.getByName("ff02::1"); - } catch (UnknownHostException e1) { - e1.printStackTrace(); - } - - running = true; - - if(role.equals("SECC")) { - - // UDP socket for SDP - try { - MulticastSocket mcSocket = new MulticastSocket(15118); - mcSocket.joinGroup(InetAddress.getByName("FF02::1")); - sdpSocket = mcSocket; - sdpThread = new UdpThread(sdpSocket); - sdpThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - - // TCP socket for V2G - try { - v2gServerSocket = new ServerSocket(v2gPort); - v2gServerThread = new TcpServerThread(v2gServerSocket); - v2gServerThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - else if(role.equals("EVCC")) { - - // UDP socket for SDP - try { - sdpSocket = new DatagramSocket(); - sdpThread = new UdpThread(sdpSocket); - sdpThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - TERFactory.getInstance().logDebug("V2Gport initialized"); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.ports.ProtocolPort#dispose() - */ - @Override - public void dispose() { - if(running) { - running = false; - if(v2gServerThread != null) { - try { - v2gServerSocket.close(); - v2gServerThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if(sdpThread != null) { - try { - sdpSocket.close(); - sdpThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - if(v2gThread != null) { - try { - v2gSocket.close(); - v2gThread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - super.dispose(); - } - - /* (non-Javadoc) - * @see org.etsi.its.adapter.layers.Layer#send(byte[], java.util.Map) - */ - @Override - public boolean send(byte[] message, Map params) { - - byte[] type = ByteHelper.extract(message, 0, 1); - byte[] v2gtpHeader = {(byte)0x01, (byte) 0xFE}; - message = ByteHelper.extract(message, 1, message.length - 1); - if(type[0] == SDP_IND) { - // SDP - byte[] sdpMessageType = null; - if(role.equals("EVCC")) { - byte[] sdpReqMessageType = {(byte)0x90, (byte)0x00}; - sdpMessageType = sdpReqMessageType; - } - else { - byte[] sdpRspMessageType = {(byte)0x90, (byte)0x01}; - sdpMessageType = sdpRspMessageType; - } - message = ByteHelper.concat(v2gtpHeader, sdpMessageType, ByteHelper.intToByteArray(message.length, 4), message); - DatagramPacket packet = new DatagramPacket(message, message.length, sdpPeerAddress, sdpPeerPort); - try { - sdpSocket.send(packet); - } catch (IOException e) { - e.printStackTrace(); - } - } - else { - // V2G or supportedAppprotocol - if(role.equals("EVCC") && v2gSocket == null) { - try { - v2gSocket = new Socket(v2gHost, v2gPort); - v2gThread = new TcpThread(v2gSocket); - v2gThread.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - byte[] exiV2gMessageType = {(byte)0x80, (byte)0x01}; - message = ByteHelper.concat(v2gtpHeader, exiV2gMessageType, ByteHelper.intToByteArray(message.length, 4), message); - v2gSocket.getOutputStream().write(message); - } catch (IOException e) { - e.printStackTrace(); - } - - v2gtpSentCount++; - if(role.equals("SECC")){ - if(v2gtpInd == APP_PROTO_IND && v2gtpReceivedCount > 0) { - v2gtpInd = V2G_IND; - ExiHelper.setSchemaId("v2g"); - } - } - } - return true; - } - - private class UdpThread extends Thread { - - private DatagramSocket taSocket; - - public UdpThread(DatagramSocket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - - while(running) { - try { - byte[] buf = new byte[4096]; - Map lowerInfo = new HashMap(); - - // receive packet - DatagramPacket packet = new DatagramPacket(buf, buf.length); - taSocket.receive(packet); - - if(role.equals("SECC")) { - sdpPeerAddress = packet.getAddress(); - sdpPeerPort = packet.getPort(); - } - lowerInfo.put(Layer.RECEPTION_TIMESTAMP, System.currentTimeMillis()); - receive(ByteHelper.concat(new byte[]{(SDP_IND)}, ByteHelper.extract(packet.getData(), packet.getOffset() + 8, packet.getLength() - 8)), lowerInfo); - } catch (IOException e) { - running = false; - } - } - taSocket.close(); - } - } - - private class TcpServerThread extends Thread { - - private ServerSocket taSocket; - - public TcpServerThread(ServerSocket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - try { - v2gSocket = taSocket.accept(); - v2gThread = new TcpThread(v2gSocket); - v2gThread.start(); - taSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private class TcpThread extends Thread { - - private Socket taSocket; - - public TcpThread(Socket taSocket) throws IOException { - this.taSocket = taSocket; - } - - @Override - public void run() { - - InputStream input = null; - try { - input = taSocket.getInputStream(); - } catch (IOException e) { - e.printStackTrace(); - } - - while(running) { - try { - byte[] buf = new byte[4096]; - int nbRead; - Map lowerInfo = new HashMap(); - - // receive packet - nbRead = input.read(buf); - if(nbRead > 8) { - ExiHelper.lockSchemaId(); - lowerInfo.put(Layer.RECEPTION_TIMESTAMP, System.currentTimeMillis()); - receive(ByteHelper.concat(new byte[]{(v2gtpInd)}, ByteHelper.extract(buf, 8, nbRead - 8)), lowerInfo); - v2gtpReceivedCount++; - if(role.equals("EVCC")){ - if(v2gtpInd == APP_PROTO_IND && v2gtpSentCount > 0) { - v2gtpInd = V2G_IND; - ExiHelper.setSchemaId("v2g"); - } - } - } - } catch (IOException e) { - e.printStackTrace(); - running = false; - } - } - try { - taSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/javasrc/certificatesio/org/etsi/certificates/CertificatesIOFactory.java b/javasrc/certificatesio/org/etsi/certificates/CertificatesIOFactory.java deleted file mode 100644 index d4cd7e87eb1787bcf511f6b91bceece8ab259db6..0000000000000000000000000000000000000000 --- a/javasrc/certificatesio/org/etsi/certificates/CertificatesIOFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.etsi.certificates; - -import org.etsi.certificates.io.CertificatesIO; -import org.etsi.certificates.io.ICertificatesIO; - -public class CertificatesIOFactory { - - /** - * The single instance of the class CertificatesIO. - */ - private static ICertificatesIO _certIO = new CertificatesIO(); - - /** - * Accessor to the single instance of this class. - * @return The single instance of this class. - */ - public static ICertificatesIO getInstance() { - return _certIO; - } - - /** - * Internal ctor (For invocation by subclass constructors, typically implicit) - */ - private CertificatesIOFactory() { - } - -} // End of class CertificatesIOFactory diff --git a/javasrc/certificatesio/org/etsi/certificates/Helpers.java b/javasrc/certificatesio/org/etsi/certificates/Helpers.java deleted file mode 100644 index 128a06badb68d9f37a235e4874ed0d87bd1ef8c2..0000000000000000000000000000000000000000 --- a/javasrc/certificatesio/org/etsi/certificates/Helpers.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id: - */ -package org.etsi.certificates; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FilenameFilter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public final class Helpers { - - - /** - * A single instance of this class - */ - private static Helpers instance; - - /** - * Synchronization object to provide single access to the instance - */ - private static Object _sync = new Object(); - - /** - * Provide the access to a single instance of this class - * @return A single instance of this class - */ - public static Helpers getInstance() { - if (instance == null) { - synchronized(_sync) { - if (instance == null) { - instance = new Helpers(); - } - } - } - - return instance; - } - - /** - * Internal ctor - */ - private Helpers() { - } - - /** - * Convert an array of strings to one string - * @param list string list - * @param separator 'separator' string between each element - * @return string list items concatenated into a string - */ - public String arrayToString(String[] list, String separator) { - StringBuffer result = new StringBuffer(); - if (list.length > 0) { - result.append(list[0]); - for (int i = 1; i < list.length; i++) { - result.append(separator); - result.append(list[i]); - } - } - - return result.toString(); - } - - /** - * Recursively walk a directory tree and return a List of all Files found; the List is sorted using File.compareTo(). - * @param p_startingDir The valid directory, which can be read. - * @param p_extension The file extension, in lower case - * @param p_excludedPatterns The pattern which shall be excluded, in lower case - */ - public List getFileListing(File p_startingDir, final String p_extension, final String[] p_excludedPatterns) throws FileNotFoundException { - validateDirectory(p_startingDir); - List result = getFileListingNoSort(p_startingDir, p_extension, p_excludedPatterns); - Collections.sort(result); - return result; - } - - private List getFileListingNoSort(final File p_startingDir, final String p_extension, final String[] p_excludedPatterns) throws FileNotFoundException { - List result = new ArrayList(); - FilenameFilter filter = new FilenameFilter() { - - @Override - public boolean accept(final File p_dirName, final String p_fileName) { - String name = p_fileName.toLowerCase(); -// TERFactory.getInstance().logDebug("getFileListingNoSort: " + name + " - " + p_extension + " - " + name.endsWith(p_extension)); - if (!p_extension.isEmpty() && !name.endsWith(p_extension)) { - return false; - } - - if (p_excludedPatterns != null) { - for (String excludePattern : p_excludedPatterns) { - if (name.indexOf(excludePattern) != -1) { -// TERFactory.getInstance().logDebug("getFileListingNoSort: exclusion criteria=" + excludePattern); - return false; - } - } - } - return true; - } - }; - File[] filesAndDirs = p_startingDir.listFiles(filter); - List filesDirs = Arrays.asList(filesAndDirs); - for (File file : filesDirs) { - result.add(file); // always add, even if directory - if (!file.isFile()) { - //must be a directory - //recursive call! - List deeperList = getFileListingNoSort(file, p_extension, p_excludedPatterns); - result.addAll(deeperList); - } - } - return result; - } - - /** - * Directory is valid if it exists, does not represent a file, and can be read. - */ - private void validateDirectory (File aDirectory) throws FileNotFoundException { - if (aDirectory == null) { - throw new IllegalArgumentException("Directory should not be null."); - } - if (!aDirectory.exists()) { - throw new FileNotFoundException("Directory does not exist: " + aDirectory); - } - if (!aDirectory.isDirectory()) { - throw new IllegalArgumentException("Is not a directory: " + aDirectory); - } - if (!aDirectory.canRead()) { - throw new IllegalArgumentException("Directory cannot be read: " + aDirectory); - } - } - -} // End of class Helpers diff --git a/javasrc/certificatesio/org/etsi/certificates/io/CertificatesIO.java b/javasrc/certificatesio/org/etsi/certificates/io/CertificatesIO.java deleted file mode 100644 index 53c0fa87e99d5d7c2d0a67d7ae180f217df627ba..0000000000000000000000000000000000000000 --- a/javasrc/certificatesio/org/etsi/certificates/io/CertificatesIO.java +++ /dev/null @@ -1,397 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.certificates.io; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.etsi.adapter.TERFactory; -import org.etsi.certificates.Helpers; -import org.etsi.common.ByteHelper; - -import de.fraunhofer.sit.c2x.CryptoLib; - -public class CertificatesIO implements ICertificatesIO { - - /** - * Extension file for certificate - */ - private static final String CERT_EXT = "crt"; - - /** - * Extension file for digests - */ - private static final String DIGESTS_EXT = "dgs"; - - /** - * Excluded files while building the lists of certificates/private keys - */ - private static final String[] EXCLUDED_PATTERNS = new String[] { /*for debug: */".svn", "._.DS_Store", ".DS_Store"}; - - /** - * Full path to access certificate files - */ - private String _fullPathCerts; - - /** - * Memory cache for the certificates - */ - private Map _cachedCertificates; - - private Map _cachedCertificatesDigest; - - private Map _cachedReverseCertificatesDigest; - - /** - * Memory cache for the signing private keys - */ - private Map _cachedSigningPrivateKey; - - /** - * Memory cache for the encrypt private keys - */ - private Map _cachedEncryptPrivateKey; - - /** - * Set to true if loadCertificates was already called - */ - private boolean _areCertificatesLoaded = false; - - /** - * Default constructor - */ - public CertificatesIO() { - _cachedCertificates = new ConcurrentHashMap(); - _cachedCertificatesDigest = new ConcurrentHashMap(); - _cachedSigningPrivateKey = new ConcurrentHashMap(); - _cachedEncryptPrivateKey = new ConcurrentHashMap(); - _cachedReverseCertificatesDigest = new ConcurrentHashMap(); - } // End of Constructor - - /** - * @desc Load in memory cache the certificates available in the specified directory - * @param rootDirectory Root directory to access to the certificates identified by the certificate ID - * @param configId A configuration identifier - * @return true on success, false otherwise - */ - @Override - public boolean loadCertificates(final String p_rootDirectory, final String p_configId) { // E.g. , cfg01 - TERFactory.getInstance().logDebug(">>> CertificatesIO.loadCertificates: '" + p_rootDirectory + "', '" + p_configId + "' - " + _areCertificatesLoaded); - - // Sanity check - if (_areCertificatesLoaded) { - return true; - } - - // Build full path - if ((p_rootDirectory == null) || (p_rootDirectory.length() == 0)) { - _fullPathCerts = System.getProperty("user.dir").replace("\\", "/"); - } else { - _fullPathCerts = p_rootDirectory.replace("\\", "/"); - } - if (!_fullPathCerts.endsWith("/")) { - _fullPathCerts += "/"; - } - - File certsPath = new File(_fullPathCerts); - if (!certsPath.exists()) { - TERFactory.getInstance().logError("CertificatesIO.loadCertificates: path '" + _fullPathCerts + "' does not found"); - return false; - } - - _areCertificatesLoaded = loadMemoryCache(certsPath); // Load certificates and keys and return - - if ((p_configId != null) && (p_configId.length() != 0)) { - String path = new String(_fullPathCerts + "/" + p_configId); - certsPath = new File(path); - if (!certsPath.exists()) { - TERFactory.getInstance().logError("CertificatesIO.loadCertificates: path '" + path + "' does not found"); - return false; - } - loadMemoryCache(certsPath); // Load certificates and keys and return - } - - return _areCertificatesLoaded; - } - - /** - * @desc Unload from memory cache the certificates available - * @return true on success, false otherwise - */ - @Override - public boolean unloadCertificates() { - _areCertificatesLoaded = false; - _fullPathCerts = null; - _cachedCertificates.clear(); - _cachedCertificatesDigest.clear(); - _cachedSigningPrivateKey.clear(); - _cachedEncryptPrivateKey.clear(); - _cachedReverseCertificatesDigest.clear(); - - return true; - } - - /** - * @desc Read the specified certificate - * @param certificateId the certificate identifier - * @param certificate the expected certificate - * @return true on success, false otherwise - */ - @Override - public boolean readCertificate(final String key, final ByteArrayOutputStream certificate) { -// TERFactory.getInstance().logDebug(">>> CertificatesIO.readCertificate: " + key); - - String certKey; - if (_cachedReverseCertificatesDigest.containsKey(key)) { - certKey = _cachedReverseCertificatesDigest.get(key); - }else{ - certKey = key; - } - - if (_cachedCertificates.containsKey(certKey)) { - try { - certificate.write(_cachedCertificates.get(certKey)); - return true; - } catch (IOException e) { - e.printStackTrace(); - } - }else{ - TERFactory.getInstance().logError("CertificatesIO.readCertificate: key '" + key + "' not found"); - } - return false; - } - - @Override - public boolean readCertificateDigest(final String certificateId, final ByteArrayOutputStream digest) { -// TERFactory.getInstance().logDebug(">>> CertificatesIO.readCertificateDigest: " + certificateId); - - // Sanity check - if (!_cachedCertificatesDigest.containsKey(certificateId)) { - TERFactory.getInstance().logError("CertificatesIO.readCertificateDigest: key '" + certificateId + "' not found"); - return false; - } - - try { - digest.write(_cachedCertificatesDigest.get(certificateId)); - return true; - - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * @desc Read the signing private key for the specified certificate - * @param keysId the keys identifier - * @param key the signing private key - * @return true on success, false otherwise - */ - @Override - public boolean readSigningKey(final String keyName, final ByteArrayOutputStream key) { -// TERFactory.getInstance().logDebug(">>> CertificatesIO.readSigningKey: " + keyName); - - try { - String certKey; - if (_cachedReverseCertificatesDigest.containsKey(keyName)) { - certKey = _cachedReverseCertificatesDigest.get(keyName); - }else{ - certKey = keyName; - } - if (_cachedSigningPrivateKey.containsKey(certKey)) { - key.write(_cachedSigningPrivateKey.get(certKey)); - return true; - } - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * @desc Read the encrypting private key for the specified certificate - * @param keysId the keys identifier - * @param key the signing private key - * @return true on success, false otherwise - */ - @Override - public boolean readEncryptingKey(final String keyName, final ByteArrayOutputStream key) { - String certKey; - try { - if (_cachedReverseCertificatesDigest.containsKey(keyName)) { - certKey = _cachedReverseCertificatesDigest.get(keyName); - }else{ - certKey = keyName; - } - if (_cachedEncryptPrivateKey.containsKey(certKey)) { - key.write(_cachedEncryptPrivateKey.get(certKey)); - return true; - } - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - - /** - * @desc Load certificates based on existing keys file, excluding xxx_at.bin files - * @param p_keysPath path for private key files - * @param p_certsPath Path for certificate files - * @return true on success, false otherwise - */ - private boolean loadMemoryCache(final File p_keysPath) { // E.g. /keys, /certs - // Retrieve the list of the files in the p_keysPath - try { - List files = Helpers.getInstance().getFileListing(p_keysPath, CERT_EXT, EXCLUDED_PATTERNS); - // Create the memory cache - for (File file : files) { - try { - addCertItem(file); - }catch(FileNotFoundException e){} - } // End of 'for' statement - - } catch (IOException e) { - e.printStackTrace(); - } - - // load digests - try { - List files = Helpers.getInstance().getFileListing(p_keysPath, DIGESTS_EXT, EXCLUDED_PATTERNS); - // Create the memory cache - for (File file : files) { - try { - addDigestItem(file); - }catch(FileNotFoundException e){} - } // End of 'for' statement - - } catch (IOException e) { - e.printStackTrace(); - } - - return true; - } - - private void addDigestItem(final File p_file) throws FileNotFoundException, IOException { - String filename = p_file.getName(); - String certName = filename.substring(0, filename.lastIndexOf(".")).toUpperCase(); - - // Load certificate - byte bytes[] = new byte[64]; - FileInputStream fs = new FileInputStream(p_file); - int n = fs.read(bytes); - fs.close(); - - if(n == 32){ - // take last 8 bytes - bytes = Arrays.copyOfRange(bytes, 24, 32); - }else if(n >= 64){ - bytes = ByteHelper.hexStringToByteArray(new String(bytes).substring(48, 64)); - }else if(n >= 16){ - bytes = ByteHelper.hexStringToByteArray(new String(bytes).substring(0, 16)); - }else if(n == 8){ - bytes = Arrays.copyOfRange(bytes, 0, 8); - }else{ - TERFactory.getInstance().logError("CertificatesIO: " + filename + ": wrong digest file length\n"); - return; - } - _cachedCertificatesDigest.put(certName, bytes); -// TERFactory.getInstance().logDebug("CertificatesIO.addDigestItem: Store digest: " + ByteHelper.byteArrayToString(bytes) + " - " + certName); - } - - private void addCertItem(final File p_certFile) throws FileNotFoundException, IOException { -// TERFactory.getInstance().logDebug(">>> CertificatesIO.addItem: " + p_certFile); - - // Load the keys file name - String filename = p_certFile.getName(); - String certName = filename.substring(0, filename.lastIndexOf(".")).toUpperCase(); - - // Load certificate - byte bytes[] = new byte[(int) p_certFile.length()]; - FileInputStream fsKeys = new FileInputStream(p_certFile); - fsKeys.read(bytes); - fsKeys.close(); - bytes = ByteHelper.hexStringToByteArray(new String(bytes)); - _cachedCertificates.put(certName, bytes); -// TERFactory.getInstance().logDebug("CertificatesIO.addItem: Store cert " + certName + " - " + ByteHelper.byteArrayToString(bytes)); - - // calculate digest - bytes = calculateDigestFromCertificate(bytes); - _cachedCertificatesDigest.put(certName, bytes); -// TERFactory.getInstance().logDebug("CertificatesIO.addItem: Store digest: " + ByteHelper.byteArrayToString(bytes) + " - " + certName); - _cachedReverseCertificatesDigest.put(ByteHelper.byteArrayToString(bytes), certName); -// TERFactory.getInstance().logDebug("CertificatesIO.addItem: Store reverse digest " + ByteHelper.byteArrayToString(bytes) + " - " + certName); - - // Load Private Keys - filename = p_certFile.getPath(); - filename = filename.substring(0, filename.lastIndexOf(".")); - - try { - File f = new File(filename+".vkey"); - if(f.exists()){ - long l = f.length(); - if(l == 32 || l == 64){ - bytes = new byte[64]; - fsKeys = new FileInputStream(f); - l = fsKeys.read(bytes); - fsKeys.close(); - if(l == 64){ - bytes = ByteHelper.hexStringToByteArray(new String(bytes)); - l = 32; - } - if(l != 32){ - TERFactory.getInstance().logError("CertificatesIO: " + f.getName() + ": wrong data length[" + l + "\n"); - } - if (!_cachedSigningPrivateKey.containsKey(certName)) { - _cachedSigningPrivateKey.put(certName, bytes); - } - }else{ - TERFactory.getInstance().logError("CertificatesIO: " + f.getName() + ": wrong key file length\n"); - } - } - }catch(FileNotFoundException e){} - - try { - File f = new File(filename+".ekey"); - if(f.exists()){ - if(f.length() == 32 || f.length() == 64){ - bytes = new byte[64]; - fsKeys = new FileInputStream(f); - fsKeys.read(bytes); - fsKeys.close(); - if(f.length() == 64){ - bytes = ByteHelper.hexStringToByteArray(new String(bytes)); - } - if (!_cachedEncryptPrivateKey.containsKey(certName)) { - _cachedEncryptPrivateKey.put(certName, bytes); - } - } - } - }catch(FileNotFoundException e){} - } - - @Override - public String getKeyIdFromHashedId8(byte[] p_hashedId8ToBeUsed) { - String key = ByteHelper.byteArrayToString(p_hashedId8ToBeUsed); - if (!_cachedReverseCertificatesDigest.containsKey(key)) { - return null; - } - - return _cachedReverseCertificatesDigest.get(key).substring(0, _cachedReverseCertificatesDigest.get(key).length() - 7/*.DIGEST*/); - } - - private byte[] calculateDigestFromCertificate(final byte[] p_toBeHashedData) { - byte[] hash = CryptoLib.hashWithSha256(p_toBeHashedData); - return ByteHelper.extract(hash, hash.length - 8, 8); - } - -} // End of class CertificatesIO diff --git a/javasrc/certificatesio/org/etsi/certificates/io/ICertificatesIO.java b/javasrc/certificatesio/org/etsi/certificates/io/ICertificatesIO.java deleted file mode 100644 index 5d3bb3934cb8859df1285282679552dad093bac8..0000000000000000000000000000000000000000 --- a/javasrc/certificatesio/org/etsi/certificates/io/ICertificatesIO.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.certificates.io; - -import java.io.ByteArrayOutputStream; - -/** - * - * @desc Interface to load certificates/private keys from disk - * - */ -public interface ICertificatesIO { - - /** - * @desc Load in memory cache the certificates available in the specified directory - * @param rootDirectory Root directory to access to the certificates identified by the certificate ID - * @param configId A configuration identifier - * @return true on success, false otherwise - */ - boolean loadCertificates(final String rootDirectory, final String configId); - - /** - * @desc Unload from memory cache the certificates - * @return true on success, false otherwise - */ - boolean unloadCertificates(); - - /** - * @desc Read the specified certificate - * @param certificateId the certificate identifier - * @param certificate the expected certificate - * @return true on success, false otherwise - */ - boolean readCertificate(final String certificateId, final ByteArrayOutputStream certificate); - - /** - * @desc Read the specified certificate digest - * @param certificateId the certificate identifier - * @param digest the expected digest - * @return true on success, false otherwise - */ - boolean readCertificateDigest(final String certificateId, final ByteArrayOutputStream digest); - - /** - * @desc Read the signing private key for the specified certificate - * @param keysId the keys identifier - * @param key the signing private key - * @return true on success, false otherwise - */ - boolean readSigningKey(final String keysName, final ByteArrayOutputStream key); - - /** - * @desc Read the encryption private key for the specified certificate - * @param keysId the keys identifier - * @param key the encrypt private key - * @return true on success, false otherwise - */ - boolean readEncryptingKey(final String keysName, final ByteArrayOutputStream key); - - /** - * @desc Retrieve the key identifier associated to the Digest value - * @param p_hashedId8ToBeUsed the Digest value - * @return The key identifier - */ - String getKeyIdFromHashedId8(final byte[] p_hashedId8ToBeUsed); - -} // End of interface ICertificatesIO diff --git a/javasrc/codec/org/etsi/codec/ITCIRequired.java b/javasrc/codec/org/etsi/codec/ITCIRequired.java deleted file mode 100644 index 612777ce03591764534da9d3ee36cad9f09a8d6e..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/codec/ITCIRequired.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.codec; - -import org.etsi.ttcn.tci.TciCDProvided; - -/** - * TCI Required interface to be implemented by TCI providers. - */ -public interface ITCIRequired { - - /** - * Get a codec instance according the the provided codec name - * @param encodingName Name of the codec to get - * @return A codec instance - */ - public TciCDProvided getCodec(final String encodingName); -} diff --git a/javasrc/codec/org/etsi/codec/ITciCDWrapper.java b/javasrc/codec/org/etsi/codec/ITciCDWrapper.java deleted file mode 100644 index c645fcc8b16fe0bed122f33bea88dc1681ea7cf4..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/codec/ITciCDWrapper.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.codec; - -import java.math.BigInteger; - -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -/** - * This interface is used to provide vendor specific implementations of TCI-CD interface - * - * Note that the TCI Codec Interface (TCI-CD) describes the operations a TTCN-3 Executable is required to implement and the operations a codec implementation for a certain encoding scheme shall provide to the TE - * - * See ETSI ES 201 873-6 V4.2.1 - Clause 7.3.2.1 TCI-CD required - */ -public interface ITciCDWrapper { - - /** - * Constructs and returns a basic TTCN-3 integer type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - * @return An instance of Type representing a TTCN-3 integer type - */ - public IntegerValue setInteger(final Integer value); - - /** - * Constructs and sets a basic TTCN-3 integer type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - */ - public void setInteger(IntegerValue intValue, final Integer value); - - /** - * Constructs and returns a basic TTCN-3 big integer type - * - * @see ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - * @return An instance of Type representing a TTCN-3 integer type - */ - public IntegerValue setInteger(final BigInteger value); - - /** - * Constructs and returns a basic TTCN-3 big integer type - * - * @see ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - * @return An instance of Type representing a TTCN-3 integer type - */ - public void setInteger(final BigInteger value, IntegerValue setInt); - - /** - * Constructs and returns a basic integer type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - * @return An instance of Type representing a TTCN-3 integer type - */ - public int getInteger(final IntegerValue iv); - - /** - * Constructs and returns a basic big integer type - * - * @see ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getInteger - * @return An instance of Type representing a TTCN-3 integer type - */ - public long/*TODO BigInteger*/ getBigInteger(final IntegerValue iv); - - /** - * Constructs and returns a basic TTCN-3 octet string type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.2 getOctetstring - * @return An instance of Type representing a TTCN-3 octet string type - */ - public OctetstringValue getOctetstring(); - - /** - * Constructs and returns a basic TTCN-3 string type - * @return An instance of Type representing a TTCN-3 string type - */ - public CharstringValue getCharstringValue(); - - /** - * Constructs and returns a basic TTCN-3 float type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.3 getFloat - * @return An instance of Type representing a TTCN-3 float type - */ - public FloatValue getFloat(); - - /** - * Constructs and returns a basic TTCN-3 float type - * - * @return An instance of Type representing a TTCN-3 float type - */ - public Value getUnionValue(final Type decodingHypothesis, final String variantName); - - /** - * Constructs and returns a basic TTCN-3 float type - * - * @return An instance of Type representing a TTCN-3 float type - */ - public RecordValue getRecordValue(final String typeName); - - /** - * Constructs and returns a basic TTCN-3 float type - * - * @return An instance of Type representing a TTCN-3 float type - */ - public RecordOfValue getRecordOfValue(final String typeName); - - /** - * Constructs and returns a basic TTCN-3 boolean type - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.1.4 getBoolean - * @return An instance of Type representing a TTCN-3 boolean type - */ - public BooleanValue getBoolean(); - - /** - * Constructs and returns a basic TTCN-3 enumerated type - * - * @return An instance of Type representing a TTCN-3 enumerated type - */ - public EnumeratedValue getEnumValue(String string); - - /** - * Convert the specified type string into a Type object - * @param type The type in string format - * @return A Type object - */ - public Type getTypeForName(final String type); - - // FIXME To be continued -} // End of interface ITciCDWrapper diff --git a/javasrc/codec/org/etsi/codec/ITciCDWrapperFactory.java b/javasrc/codec/org/etsi/codec/ITciCDWrapperFactory.java deleted file mode 100644 index bf186ad55476c6eb82bb6a384da5788be9e683de..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/codec/ITciCDWrapperFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.codec; - - - -/** This interface provides mandatory method to be used by Vendor to implement specific TEE part of code for TciCD - * - * See ETSI ES 201 873-6 V4.2.1 - Clause 7.3.2.1 TCI-CD required - */ -public interface ITciCDWrapperFactory { - - /** - * This method is used by Vendor to implement specific TEE part of code for TciCD - * - * @param tcicd A n instance of TciCDWrapper - * @see ITciCDWrapper - */ - public void setImpl(final ITciCDWrapper tcicd); - -} // End of interface ITciCDWrapperFactory diff --git a/javasrc/codec/org/etsi/codec/TciCDWrapperFactory.java b/javasrc/codec/org/etsi/codec/TciCDWrapperFactory.java deleted file mode 100644 index 16496b6faf7b5157d34316a7ae5b8f6e2093e5e0..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/codec/TciCDWrapperFactory.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.codec; - - - -/** - * This class implements ITciCDWrapperFactory interface - * - * @see ITciCDWrapperFactory - * @category factory - */ -public class TciCDWrapperFactory implements ITciCDWrapperFactory{ - - /** - * Unique instance of this class - */ - private static ITciCDWrapperFactory _instanceFactory = (ITciCDWrapperFactory)new TciCDWrapperFactory(); - - /** - * Unique instance of TciCDWrapper class - * @see setImpl - */ - private static ITciCDWrapper _instance; - - /** - * Default internal ctor - */ - private TciCDWrapperFactory() { - //empty - } - - /** - * Singleton access method - * - * @return A unique reference to this class - */ - public static ITciCDWrapperFactory getInstance() { - return _instanceFactory; - } - - /** - * Singleton access method - * - * @return A unique reference to the TciCDWrapper class - */ - public static ITciCDWrapper getTciCDInstance() { - return _instance; - } - - /** - * This method is used by Vendor to implement specific TEE part of code for TciCD - * - * @param tcicd A n instance of TciCDWrapper - * @see ITciCDWrapper - */ - @Override - public void setImpl(final ITciCDWrapper tcicd) { - _instance = tcicd; - } - -} // End of class TciCDWrapperFactory diff --git a/javasrc/codec/org/etsi/ttcn/codec/CodecBuffer.java b/javasrc/codec/org/etsi/ttcn/codec/CodecBuffer.java deleted file mode 100644 index 3d180115c0fc30ef10a9e7ed6240a41a97e28b37..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/CodecBuffer.java +++ /dev/null @@ -1,516 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -import java.util.Map; -import java.util.TreeMap; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; - -public class CodecBuffer { - - /** - * Raw byte storage array. Last byte may be a "partial byte", i.e. some of its bits may not be significants - * @see bits - */ - protected byte[] buffer; - - /** - * Number of significant bits in the "partial byte" - * Significant bits are always stored "left-aligned" (i.e. MSBs) in the "partial byte" - * @see buffer - */ - protected int bits; - - /** - * Marker storage - */ - protected Map markers = new TreeMap(); - - /** - * Some useful byte masks - */ - private byte[] masks = new byte[]{(byte)0x00, (byte)0x80, (byte)0xC0, (byte)0xE0, (byte)0xF0, (byte)0xF8, (byte)0xFC, (byte)0xFE}; - - /** - * Some useful byte masks - */ - private byte[] nomasks = new byte[]{(byte)0xFF, (byte)0x7F, (byte)0x3F, (byte)0x1F, (byte)0x0F, (byte)0x07, (byte)0x03, (byte)0x01}; - - /** - * Main constructor. Initialises an empty buffer - */ - public CodecBuffer() { - bits = 0; - buffer = new byte[]{}; - } - - /** - * Constructor. Initialises the buffer using provided byte array - * @param bytes Initial content of the buffer - */ - public CodecBuffer(byte[] bytes) { - bits = 0; - buffer = bytes.clone(); - } - - /** - * Overwrite content of current buffer using data of newBuffer - * @param newBuffer CodecBuffer containing new data - */ - public void overwriteWith(CodecBuffer newBuffer) { - - bits = newBuffer.bits; - buffer = newBuffer.buffer.clone(); - markers = new TreeMap(newBuffer.markers); - } - - /** - * Retrieves the number of significant bits in the buffer. - * Warning: getNbBytes() != (getNbBits() * 8) - * @return The number of significant bits in the buffer - * @see getNbBytes() - */ - public int getNbBits() { - - if(bits > 0) { - return (buffer.length - 1) * 8 + bits; - } - return buffer.length * 8; - } - - /** - * Retrieves the number of bytes used to store the buffer. - * Warning: getNbBytes() != (getNbBits() * 8) - * @return The number of bytes used to store the buffer - * @see getNbBits() - */ - public int getNbBytes() { - return buffer.length; - } - - /** - * Concatenates current CodecBuffer and the CodecBuffer passed as parameter. - * Markers of buffer2 are preserved and integrated into the current CodecBuffer. - * @param buffer2 The CodecBuffer to be appended - */ - public void append(CodecBuffer buffer2) { - - // copy buffer content - int nbBits = getNbBits(); - if(buffer2.getNbBits() > 0) { - appendBits(buffer2.getBits(), buffer2.getNbBits()); - } - - // integrate markers - for(Map.Entry entry : buffer2.markers.entrySet()) { - String key = entry.getKey(); - Marker marker = entry.getValue(); - marker.move(nbBits); - markers.put(key, marker); - } - } - - /** - * Associates a new marker to current CodecBuffer. - * Inserting marker with name identical to a previously inserted one will overwrite it. - * @param key Name of the marker - * @param pos Position of the marker relative to the current position - * @param callback Optional callback object to be executed later, or null - * @see runCallbacks() - */ - public void setMarker(String key, int pos, IMarkerCallback callback) { - markers.put(key, new Marker(pos, callback)); - } - - /** - * Executes all the callbacks associated to current CodecBuffer's markers - * @see setMarkers() - */ - public void runCallbacks() { -// TERFactory.getInstance().logDebug("Running callbacks..."); - for(Map.Entry entry : markers.entrySet()) { - String key = entry.getKey(); -// TERFactory.getInstance().logDebug("Running callback: " + key); - Marker marker = entry.getValue(); - IMarkerCallback callback = marker.getCallback(); - if(callback != null) { - CodecBuffer Left = getBuffer(0, marker.getPos()); - CodecBuffer Right = getBuffer(marker.getPos(), getNbBits() - marker.getPos()); - - callback.run(key, Left, Right); - - // Overwrite self with Left+Right - // TODO: take care if Right or Left have change to much. - Left.append(Right); - buffer = Left.buffer; - bits = Left.bits; - } - } - } - - /** - * Creates a new CodecBuffer from current CodecBuffer's content - * Markers of current CodecBuffer are preserved and integrated into the new CodecBuffer. - * @param start Start point. Bit offset from current position - * @param length Amount of bits to be copied - * @return The new CodecBuffer - */ - public CodecBuffer getBuffer(int start, int length) { - // TODO: check param validity - - CodecBuffer res = new CodecBuffer(); - res.setBits(getBits(start, length), length); - - for(Map.Entry entry : markers.entrySet()) { - String key = entry.getKey(); - Marker marker = entry.getValue(); - int pos = marker.getPos(); - if(pos >= start && pos < (start + length)) { - res.setMarker(key, pos - start, marker.getCallback()); - } - } - return res; - } - - /** - * Appends some raw bytes at the end of the current CodecBuffer - * @param origBytes Bytes to be appended - */ - public void appendBytes(byte[] origBytes) { - - byte[] bytes = origBytes.clone(); - - int lastByte = buffer.length - 1; - buffer = ByteHelper.concat(buffer, bytes); - - if(bits != 0) { - for(int i=0; i < bytes.length; i++) { - buffer[lastByte] &= masks[bits]; - buffer[lastByte] |= ((bytes[i] >>> bits) & nomasks[bits]); - lastByte++; - buffer[lastByte] = (byte)(buffer[lastByte] << (8 - bits)); - } - - buffer[buffer.length - 1] &= masks[bits]; - } - } - - /** - * Appends some raw bits at the end of the current CodecBuffer - * @param origBytes Byte array used to store the bits to be appended. - * It MUST be right-aligned. First byte (origBytes[0]) may be a - * partial byte if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are ignored and not copied - * @param nbBits Number of significant bits in 'origBytes' - */ - public void appendBits(byte[] origBytes, int nbBits) { - - byte[] bytes = origBytes.clone(); - int rbits = nbBits % 8; - int nbBytes = nbBits / 8 + ((rbits > 0)?1:0); - int lastByte = buffer.length - 1; - - // Left-align received bytes - if(rbits !=0) { - int i; - for(i=(bytes.length - nbBytes); i < (nbBytes - 1); i++) { - bytes[i] = (byte)(bytes[i] << (8 - rbits)); - bytes[i] |= ((bytes[i+1] >>> rbits) & nomasks[rbits]); - } - bytes[i] = (byte)(bytes[i] << (8 - rbits)); - bytes[i] &= masks[rbits]; - } - - buffer = ByteHelper.concat(buffer, ByteHelper.extract(bytes, (bytes.length - nbBytes), nbBytes)); - if(bits != 0) { - int i; - for(i=lastByte; i < (lastByte + nbBytes); i++) { - buffer[i] &= masks[bits]; - buffer[i] |= ((buffer[i+1] >>> bits) & nomasks[bits]); - buffer[i+1] = (byte)(buffer[i+1] << (8 - bits)); - } - buffer[i] &= masks[bits]; - - if((rbits > 0) && (rbits + bits <= 8)) { - // Remove trailing byte (garbage) - buffer = ByteHelper.extract(buffer, 0, buffer.length - 1); - } - - } - - bits += nbBits; - bits %= 8; - } - - /** - * Overwrite the content of CodecBuffer using the provided bytes - * @param bytes New content of the CodecBuffer - * @see setBits() - */ - public void setBytes(byte[] bytes) { - buffer = bytes.clone(); - bits = 0; - markers.clear(); - } - - /** - * Overwrite the content of CodecBuffer using the provided bits - * @param bytes Byte array used to store the bits to be used. - * It MUST be right-aligned. First byte (origBytes[0]) may be a - * partial byte if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are ignored and not copied - * @param nbBits Number of significant bits in 'bytes' - * @see setBytes() - */ - public void setBits(byte[] bytes, int nbBits) { - - if(nbBits == 0) { - bits = 0; - buffer = new byte[]{}; - } - else { - int i; - int rbits = nbBits % 8; - int nbBytes = nbBits / 8 + ((rbits > 0)?1:0); - bits = rbits; - buffer = bytes.clone(); - - if(bits !=0) { - for(i=(bytes.length - nbBytes); i < (nbBytes - 1); i++) { - buffer[i] = (byte)(buffer[i] << (8 - bits)); - buffer[i] |= ((buffer[i+1] >>> bits) & nomasks[bits]); - } - buffer[i] = (byte)(buffer[i] << (8 - bits)); - buffer[i] &= masks[bits]; - } - } - markers.clear(); - } - - /** - * Extracts some bytes at the beginning of the buffer. Read bytes are discarded from the buffer. - * @param nbBytes Number of bytes to be read - * @return Byte array containing the 'nbBytes' first bytes of the buffer. - * Byte array's length may be shorter than requested if buffer does not - * contain enough bytes - * @see getBytes() - */ - public byte[] readBytes(int nbBytes) { - byte[] result = getBytes(0, nbBytes); - int newLength = getNbBits() - (nbBytes * 8); - - if(result != null) { - if(newLength > 0) { - setBits(getBits(nbBytes * 8, newLength), newLength); - } - else { - bits = 0; - buffer = new byte[] {}; - } - } else { - result = new byte[] {}; - } - return result; - // TODO: move markers - } - - /** - * Extracts some bits at the beginning of the buffer. Read bits are discarded from the buffer. - * @param nbBytes Number of bits to be read - * @return Byte array containing the 'nbBits' first bits of the buffer. - * Number of returned bits may be smaller than requested if buffer does not - * contain enough bits. Returned byte array is right-aligned. - * First byte may be a partial byte if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are not significants and padded with '0's - * @see getBits() - */ - public byte[] readBits(int nbBits) { - byte[] result = getBits(0, nbBits); - int newLength = getNbBits() - nbBits; - byte[] newBuffer = getBits(nbBits, newLength); - - if(result != null) { - setBits(newBuffer, newLength); - } - return result; - // TODO: move markers - } - - /** - * Retrieves the raw content of the CodecBuffer - * @return Raw byte array used to store CodecBuffer's content - * Returned byte array is left-aligned. - * Last byte may be a partial byte if 'bits' is not null. - * In this case LSBs of this byte are not significants and their value is undetermined - */ - public byte[] getBytes() { - return buffer; - } - - /** - * Retrieves some bytes from the CodecBuffer. Returned bytes are not removed from the buffer - * @param start Start point (octet index) - * @param nbBytes Number of bytes to be returned - * @return Extracted bytes. - * Returned byte array is left-aligned. - * Last byte may be a "partial byte" if it is the last byte of CodecBuffer and if 'bits' is not null. - * In this case LSBs of this byte are not significants and their value is undetermined - * @see ReadBytes() - */ - public byte[] getBytes(int start, int nbBytes) { - - if(start > buffer.length) { - TERFactory.getInstance().logDebug("bad start: " + start); - return null; - } - if((start + nbBytes) > buffer.length) { - TERFactory.getInstance().logDebug("bad length: " + (start + nbBytes) + " (" + buffer.length + " bytes remaining)"); - return null; - } - - if(nbBytes < 0) { - TERFactory.getInstance().logDebug("bad length: " + (nbBytes) + " (" + buffer.length + " bytes remaining)"); - return null; - } - - return ByteHelper.extract(buffer, start, nbBytes); - } - - /** - * Retrieves all the bits from the CodecBuffer. Returned bits are not removed from the buffer - * @return Extracted bits stored in a byte array. - * Returned byte array is right-aligned. - * First byte may be a "partial byte" if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are not significants and their value is '0' - * @see ReadBits() - */ - public byte[] getBits() { - return getBits(0, getNbBits()); - } - - /** - * Retrieves some bits from the CodecBuffer. Returned bits are not removed from the buffer - * @param start Start point (bit index) - * @param nbBits Number of bits to be returned - * @return Extracted bits stored in a byte array. - * Returned byte array is right-aligned. - * First byte may be a "partial byte" if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are not significants and their value is '0' - * @see ReadBits() - */ - public byte[] getBits(int start, int nbBits) { - - int byteIndex = start / 8; - int bitOffset = start % 8; - int nbBytes = ((bitOffset > 0)?1:0) + (((nbBits - 8 + bitOffset) / 8) + ((bitOffset==0)?1:0)) + ((((nbBits - 8 + bitOffset) % 8) > 0)?1:0); - // leading partial byte complete bytes trailing partial byte - - if(byteIndex > buffer.length) { - TERFactory.getInstance().logDebug("bad start: " + byteIndex + "(" + start + ")" + " (" + buffer.length + " bytes remaining)"); - return null; - } - if((byteIndex + nbBytes) > buffer.length) { - TERFactory.getInstance().logDebug("bad length: " + (byteIndex + nbBytes) + "(" + nbBits + ")" + " (" + buffer.length + " bytes remaining)"); - return null; - } - - byte[] tmp = ByteHelper.extract(buffer, byteIndex, nbBytes); - - if(bitOffset != 0) { - tmp[0] = (byte)(tmp[0] << bitOffset); - for(int i=1; i < tmp.length; i++) { - tmp[i-1] &= masks[8 - bitOffset]; - tmp[i-1] |= ((tmp[i] >>> (8 - bitOffset)) & nomasks[8 - bitOffset]); - tmp[i] = (byte)(tmp[i] << bitOffset); - } - } - - tmp = ByteHelper.extract(tmp, 0, nbBits / 8 + (((nbBits % 8) > 0)?1:0)); - - if(nbBits % 8 > 0) { - for(int i=tmp.length-1; i >= 0; i--) { - tmp[i] = (byte)((tmp[i] >>> (8 - (nbBits % 8))) & nomasks[8 - (nbBits % 8)]); - if(i > 0) { - tmp[i] |= (byte)(tmp[i-1] << (nbBits % 8)); - } - } - } - - return tmp; - } - - /** - * Retrieves some bits from the CodecBuffer. Returned bits are not removed from the buffer - * @param markerKey Name of the marker serving as starting point for the extraction - * @param nbBits Number of bits to be returned - * @return Extracted bits stored in a byte array. - * Returned byte array is right-aligned. - * First byte may be a "partial byte" if 'nbBits' is not a multiple of 8. - * In this case MSBs of this byte are not significants and their value is '0' - * @see ReadBits() - */ - public byte[] getBits(String markerKey, int nbBits) { - Marker marker = markers.get(markerKey); - - if(marker != null) { - return getBits(marker.getPos(), nbBits); - } - return null; - } - - /** - * Private class used to represent markers that can be insterted in CodecBuffer - */ - private class Marker { - - /** - * Constructor. - * @param pos Position of the marker relative to the current position - * @param callback Optional callback object to be executed later, or null - */ - public Marker(int pos, IMarkerCallback callback) { - this.pos = pos; - this.callback = callback; - } - - /** - * Retrieve the position of the marker (bit offset from buffer's start). - * @return The position of the marker - */ - public int getPos() { - return pos; - } - - /** - * Retrieve the callback object associated to the marker. - * @return The callback object associated to the marker, or null - */ - public IMarkerCallback getCallback() { - return callback; - } - - /** - * Changes the position of the marker in the buffer - * @param nbBits Position offset from marker's current position (can be negative) - */ - public void move(int nbBits) { - pos += nbBits; - } - - /** - * Current position of the marker - */ - private int pos; - - - /** - * Callback object associated to the marker - */ - private IMarkerCallback callback; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/CodecFactory.java b/javasrc/codec/org/etsi/ttcn/codec/CodecFactory.java deleted file mode 100644 index 90892f875a389b39e37e448d177340b2b6653bdf..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/CodecFactory.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -import java.lang.reflect.Constructor; -import java.util.Map; -import java.util.TreeMap; - -import org.etsi.adapter.TERFactory; -import org.etsi.ttcn.tci.TciCDProvided; -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.generic.Bitstring; -import org.etsi.ttcn.codec.generic.Boolean; -import org.etsi.ttcn.codec.generic.Charstring; -import org.etsi.ttcn.codec.generic.Octetstring; -import org.etsi.ttcn.codec.generic.Integer; -import org.etsi.ttcn.codec.generic.Set; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.generic.RecordOf; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.generic.Enumerated; -import org.etsi.ttcn.codec.generic.Dummy; - -public class CodecFactory { - - private static CodecFactory instance = new CodecFactory(); - private static boolean initialized = false; - protected Map> codecs = new TreeMap>(); - protected Map externalCodecs = new TreeMap(); - - private CodecFactory() { - codecs.put(TciTypeClass.BITSTRING + "//", Bitstring.class); - codecs.put(TciTypeClass.OCTETSTRING + "//", Octetstring.class); - codecs.put(TciTypeClass.CHARSTRING + "//", Charstring.class); - codecs.put(TciTypeClass.RECORD + "//", Record.class); - codecs.put(TciTypeClass.SET + "//", Set.class); - codecs.put(TciTypeClass.INTEGER + "//", Integer.class); - codecs.put(TciTypeClass.FLOAT + "//", org.etsi.ttcn.codec.generic.Float.class); - codecs.put(TciTypeClass.UNION + "//", Union.class); - codecs.put(TciTypeClass.ENUMERATED + "//", Enumerated.class); - codecs.put(TciTypeClass.RECORD_OF + "//", RecordOf.class); - codecs.put(TciTypeClass.SET_OF + "//", RecordOf.class); - codecs.put(TciTypeClass.BOOLEAN + "//", Boolean.class); - - } - - public static CodecFactory getInstance() { - - instance.initialize(); - return instance; - } - - public void initialize() { - - if(!initialized) { - initialized = true; - - // FIXME: dynamic - // initialize additional codec plugins - org.etsi.ttcn.codec.its.adapter.Plugin.init(); - org.etsi.ttcn.codec.its.uppertester.Plugin.init(); - org.etsi.ttcn.codec.its.configtester.Plugin.init(); - org.etsi.ttcn.codec.its.geonetworking.Plugin.init(); - org.etsi.ttcn.codec.its.btp.Plugin.init(); - org.etsi.ttcn.codec.its.security.Plugin.init(); - org.etsi.ttcn.codec.its.facilities.Plugin.init(); - } - - } - - public TciCDProvided getExternalCodec(String encoding) { - TciCDProvided codec = null; - - if(encoding == null) { - return null; - } - - //TERFactory.getInstance().logDebug("getExternalCodec: Search external codec for " + encoding); - codec = externalCodecs.get(encoding); - if(codec != null) { - //TERFactory.getInstance().logDebug(String.format("%50s", encoding)); - //TERFactory.getInstance().logDebug(" ==> " + codec.getClass().getName()); - System.out.println(String.format("%50s", encoding) + " ==> " + codec.getClass().getName()); - return codec; - } - return null; - } - - public ICodec getCodec(MainCodec mainCodec, int classType, String encoding, String typeName) { - - //TERFactory.getInstance().logDebug(String.format("%50s", typeName + "(" + encoding + ")")); - System.out.println(String.format("%50s", typeName + "(" + encoding + ")")); - Class cls = null; - Class[] ctorParams = {MainCodec.class}; - - //TERFactory.getInstance().logDebug("getCodec: Search internal codec for " + classType + '/' + encoding + '/' + typeName); - System.out.println("getCodec: Search internal codec for " + classType + '/' + encoding + '/' + typeName); - cls = codecs.get(classType + '/' + encoding + '/' + typeName); - if(cls == null) { - cls = codecs.get(classType + '/' + encoding + '/'); - } - if(cls == null) { - cls = codecs.get(classType + "//"); - } - - if(cls != null) { - //TERFactory.getInstance().logDebug(" ==> " + cls.getName()); - System.out.println(" ==> " + cls.getName()); - try { - Constructor ctor = cls.getConstructor(ctorParams); - return ctor.newInstance(mainCodec); - } - catch (Exception ex) { - ex.printStackTrace(); - } - } - - //TERFactory.getInstance().logDebug(" ==> No codec found !"); - System.out.println(" ==> No codec found !"); - return new Dummy(mainCodec); - } - - public void setCodec(int classType, String encoding, String typeName, Class codec) { - //TERFactory.getInstance().logDebug("setCodec: add " + classType + "/" + encoding + "/" + typeName + "/" + codec); - codecs.put(classType + '/' + encoding + '/' + typeName, codec); - } - - public void setExternalCodec(String encoding, TciCDProvided codec) { - externalCodecs.put(encoding, codec); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ICodec.java b/javasrc/codec/org/etsi/ttcn/codec/ICodec.java deleted file mode 100644 index af9dcee31a21b1b8061fefe3ea57e2b89853795b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ICodec.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ICodec { - - public ICodec(MainCodec mainCodec) { - this.mainCodec = mainCodec; - this.len = -1; - } - - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - return null; - } - - public CodecBuffer encode(Value value) { - return null; - } - - protected int getVariantBitLength(String variant) { - try { - Matcher matcher = PATTERN_VARIANT.matcher(variant); - if(matcher.find()) { - if (matcher.group(3) != null) - return java.lang.Integer.parseInt(matcher.group(3)); - else - return java.lang.Integer.parseInt(matcher.group(7)); - } - } - catch(Exception e) { - // Empty on purpose - } - return 0; - } - - protected int getEncodingLength(String encoding) { - try { - Matcher matcher = PATTERN_ENCODING.matcher(encoding); - if(matcher.find()) { - return java.lang.Integer.parseInt(matcher.group(1)); - } - } - catch(Exception e) { - // Empty on purpose - } - return 0; - } - - protected void setLength(int len) { - this.len = len; - } - - protected int getLength() { - return len; - } - - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - return; - } - - public CodecBuffer preEncode(Value value) { - return null; - } - - protected final static Pattern PATTERN_VARIANT = Pattern.compile("((\\w+)\\s+)?((\\d+))\\s+bit|(\\w{0,1})(Int)(\\d+)"); - protected final static Pattern PATTERN_ENCODING = Pattern.compile("length\\((\\d+)\\)"); - protected MainCodec mainCodec; - private int len; - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/IMarkerCallback.java b/javasrc/codec/org/etsi/ttcn/codec/IMarkerCallback.java deleted file mode 100644 index 2f37c6d55cb69272342c6fbd6a6e5869e37a1f26..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/IMarkerCallback.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -public interface IMarkerCallback { - - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf); - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ITERequired.java b/javasrc/codec/org/etsi/ttcn/codec/ITERequired.java deleted file mode 100644 index 26f8c8ff4943d74d13533d284a274646e31135fb..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ITERequired.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -import org.etsi.ttcn.tci.Type; - -public interface ITERequired { - - public Type getTypeForName(String typeName); - public Type getInteger(); - public Type getFloat(); - public Type getBoolean(); - public Type getCharstring(); - public Type getUniversalCharstring(); - public Type getHexstring(); - public Type getBitstring(); - public Type getOctetstring(); - public Type getVerdict(); - public void tciErrorReq(String message); -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/MainCodec.java b/javasrc/codec/org/etsi/ttcn/codec/MainCodec.java deleted file mode 100644 index 0377d9007dfdbdeaec6cefc65763e8f847d5525d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/MainCodec.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -import java.util.Map; -import java.util.TreeMap; - -import org.etsi.codec.ITciCDWrapper; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.TciCDProvided; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -public class MainCodec extends ICodec { - - public MainCodec(ITciCDWrapper _cdReq) { - super(null); - this.cdReq = _cdReq; - } - - public Value triDecode(TriMessage message, Type decodingHypothesis) { - return decode(new CodecBuffer(message.getEncodedMessage()), decodingHypothesis); - } - - public TriMessage triEncode(Value value) { - CodecBuffer encoded = encode(value); - encoded.runCallbacks(); - return new TriMessageImpl(encoded.getBytes()); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> MainCodec.decode: " + decodingHypothesis.getName()); -// ByteHelper.dump(">>> MainCodec.decode: ", buf.getBytes()); - - CodecFactory cf = CodecFactory.getInstance(); - try { - TciCDProvided extCodec = cf.getExternalCodec(decodingHypothesis.getTypeEncoding()); - if(extCodec != null) { - return extCodec.decode(new TriMessageImpl(buf.getBytes()), decodingHypothesis); - } - ICodec codec = cf.getCodec( - this, - decodingHypothesis.getTypeClass(), - decodingHypothesis.getTypeEncoding(), - decodingHypothesis.getName() - ); - codec.preDecode(buf, decodingHypothesis); - - // TODO To be removed, for debug purpose only -// Value decValue = codec.decode(buf, decodingHypothesis); -// TERFactory.getInstance().logDebug("<<< MainCodec.decode: " + decValue); -// return decValue; - return codec.decode(buf, decodingHypothesis); - } catch(Throwable e) { - e.printStackTrace(); - return null; - } - } - - @Override - public CodecBuffer encode(Value value) { - //TERFactory.getInstance().logDebug(">>> MainCodec.encode: " + value); - //System.out.println(">>> MainCodec.encode: " + value); - - CodecFactory cf = CodecFactory.getInstance(); - TciCDProvided extCodec = cf.getExternalCodec(value.getValueEncoding()); - if(extCodec != null) { - TriMessage enc = extCodec.encode(value); - if (enc != null) { - return new CodecBuffer(enc.getEncodedMessage()/*extCodec.encode(value).getEncodedMessage()*/); - } // else continue - } - ICodec codec = CodecFactory.getInstance().getCodec( - this, - value.getType().getTypeClass(), - value.getValueEncoding(), - value.getType().getName() - ); - CodecBuffer preBuf = codec.preEncode(value); - CodecBuffer buf = codec.encode(value); - if(preBuf != null) { - preBuf.append(buf); - buf = preBuf; - } - - //ByteHelper.dump("<<< MainCodec.encode: ", buf.getBytes()); - return buf; - } - - public String getHint(String key) { -// TERFactory.getInstance().logDebug("getHint: " + key + ": " + hints.get(key)); - return hints.get(key); - } - - public void setHint(String key, String value) { -// TERFactory.getInstance().logDebug("setHint: " + key + ", " + value); - hints.put(key, value); - } - - public java.lang.Boolean getPresenceHint(String key) { -// TERFactory.getInstance().logDebug("getPresenceHint: " + key + ": " + presenceHints.get(key)); - return presenceHints.get(key); - } - - public void setPresenceHint(String key, java.lang.Boolean value) { -// TERFactory.getInstance().logDebug("setPresenceHint: " + key + ", " + value); - presenceHints.put(key, value); - } - - public ITciCDWrapper getTciCDRequired() { - return cdReq; - } - - protected Map hints = new TreeMap(); - protected Map presenceHints = new TreeMap(); - protected ITciCDWrapper cdReq; -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/TERFactory.java b/javasrc/codec/org/etsi/ttcn/codec/TERFactory.java deleted file mode 100644 index 4bada340f655a9b8351f3c156f38b07ad46d4b82..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/TERFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; - -public class TERFactory { - - private static ITERequired instance; - - public static ITERequired getInstance() { - return instance; - } - - private TERFactory() { - - } - - public static void setImpl(ITERequired impl) { - instance = impl; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/TriMessageImpl.java b/javasrc/codec/org/etsi/ttcn/codec/TriMessageImpl.java deleted file mode 100644 index 7dbc2a1a1bde791ed489f9b689e82e78bfaec1a3..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/TriMessageImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec; // TODO: use TriMessage implementation provided by tool - -import org.etsi.ttcn.tri.TriMessage; - -public class TriMessageImpl implements TriMessage { - - /** - * - */ - private static final long serialVersionUID = -2657880550149993668L; - private byte[] message; - - public TriMessageImpl(byte[] message) { - this.message = message; - } - - @Override - public boolean equals(TriMessage message) { - return java.util.Arrays.equals(this.message, message.getEncodedMessage()) && getNumberOfBits() == message.getNumberOfBits(); - } - - @Override - public byte[] getEncodedMessage() { - return this.message; - } - - @Override - public int getNumberOfBits() { - return this.message.length * Byte.SIZE; - } - - @Override - public void setEncodedMessage(byte[] message) { - this.message = message; - } - - @Override - public void setNumberOfBits(int amount) { - int length = amount / 8; - if(this.message == null) { - if ((amount % 8) != 0) { - length += 1; - } - this.message = new byte[length]; - } - else if(this.message.length > length) { - throw new UnsupportedOperationException(); - } - else if (this.message.length < length) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Bitstring.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Bitstring.java deleted file mode 100644 index ab44105670785d3995e046e850f137aebb4df24c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Bitstring.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.BitstringValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - - -public class Bitstring extends ICodec { - - public Bitstring(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> Bitstring.decode: " + decodingHypothesis.getTypeEncoding()); - - BitstringValue bv = (BitstringValue)decodingHypothesis.newInstance(); - int lengthInBits = getEncodingLength(decodingHypothesis.getTypeEncoding()); -// TERFactory.getInstance().logDebug("Bitstring.decode: lengthInBits=" + lengthInBits); - CodecBuffer value = new CodecBuffer(); - value.setBits(buf.readBits(lengthInBits), lengthInBits); - - bv.setLength(lengthInBits); - - for(int i=0; i < lengthInBits; i++) { - bv.setBit(i, value.readBits(1)[0]); - } - - return bv; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> Bitstring.encode: " + value); - - BitstringValue bv = (BitstringValue)value; - CodecBuffer encoded = new CodecBuffer(); - - for(int i=0; i < bv.getLength(); i++) { - encoded.appendBits(new byte[]{(byte)bv.getBit(i)}, 1); - } - - return encoded; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Boolean.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Boolean.java deleted file mode 100644 index 78c801953889555b4eb8489e972750ebe3a8c5c5..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Boolean.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class Boolean extends ICodec { - - public Boolean(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - BooleanValue bv = (BooleanValue)decodingHypothesis.newInstance(); - byte[] value = buf.readBits(8); - - if(value[0] > 0) { - bv.setBoolean(true); - } - else { - bv.setBoolean(false); - } - return bv; - } - - @Override - public CodecBuffer encode(Value value) { - - BooleanValue bv = (BooleanValue)value; - CodecBuffer encoded = new CodecBuffer(); - - if(bv.getBoolean() == true) { - encoded.appendBytes(new byte[] {(byte)0x01}); - } - else { - encoded.appendBytes(new byte[] {(byte)0x00}); - } - - return encoded; - } - - -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Charstring.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Charstring.java deleted file mode 100644 index 2fb05fad1be89a04689654b7cae85e5a61b7cd4c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Charstring.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Charstring extends ICodec { - - public Charstring(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - CharstringValue cv = (CharstringValue)decodingHypothesis.newInstance(); - int lengthInBytes = 0; - - // Get length - String hint = mainCodec.getHint(decodingHypothesis.getName() + "Len"); - if(hint == null) { - lengthInBytes = getEncodingLength(decodingHypothesis.getTypeEncoding()); - } - else { - lengthInBytes = java.lang.Integer.parseInt(hint); - } - - byte[] value = buf.readBytes(lengthInBytes); - - cv.setLength(lengthInBytes); - for(int i=0; i < value.length; i++) { - cv.setChar(i, (char)value[i]); - } - - return cv; - } - - @Override - public CodecBuffer encode(Value value) { - - CharstringValue cv = (CharstringValue)value; - byte[] encoded = new byte[] {}; - if (cv.getString() != null) { - encoded = cv.getString().getBytes(); - } - - return new CodecBuffer(encoded); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Dummy.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Dummy.java deleted file mode 100644 index de663b4d60b1cb2dce0c505aa2965d31663af8a9..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Dummy.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Dummy extends ICodec { - - public Dummy(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - return decodingHypothesis.newInstance(); - } - - @Override - public CodecBuffer encode(Value value) { - - return new CodecBuffer(new byte[]{(byte)0x00}); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Enumerated.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Enumerated.java deleted file mode 100644 index 3b9e00ff9078935d3c2dd668ea96966907f6abe8..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Enumerated.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Enumerated extends ICodec { - - public Enumerated(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> Enumerated.decode: " + decodingHypothesis.getName()); - - EnumeratedValue ev = (EnumeratedValue)decodingHypothesis.newInstance(); - int lengthInBits = 0; - - // Get length - String hint = mainCodec.getHint(decodingHypothesis.getName() + "Len"); - if(hint == null) { - lengthInBits = getVariantBitLength(decodingHypothesis.getTypeEncodingVariant()); - } - else { - lengthInBits = java.lang.Integer.parseInt(hint); - } - - byte[] value = buf.readBits(lengthInBits); - ev.setInt(ByteHelper.byteArrayToInt(value)); - - return ev; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> Enumerated.encode: " + value.getType().getName()); - - EnumeratedValue ev = (EnumeratedValue)value; - int lengthInBits = 0; - int lengthInBytes = 0; - CodecBuffer encoded = new CodecBuffer(); - - // Get length - String hint = mainCodec.getHint(value.getType().getName() + "Len"); - if(hint == null) { - lengthInBits = getVariantBitLength(value.getType().getTypeEncodingVariant()); - } - else { - lengthInBits = java.lang.Integer.parseInt(hint); - } - lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - encoded.setBits(ByteHelper.intToByteArray(ev.getInt(), lengthInBytes), lengthInBits); - - return encoded; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Float.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Float.java deleted file mode 100644 index 66aae1f89815490d7838b86cfe57ded8f1abfd65..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Float.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class Float extends ICodec { - - public Float(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> Float.decode: " + decodingHypothesis.getName()); - - FloatValue fv = mainCodec.getTciCDRequired().getFloat(); - fv.setFloat(ByteHelper.byteArrayToFloat(buf.readBits(java.lang.Float.SIZE))); - -// TERFactory.getInstance().logDebug("<<< Float.decode: " + fv.getFloat()); - return fv; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> Float.encode: " + value.getType().getName()); - - FloatValue fv = (FloatValue)value; -// TERFactory.getInstance().logDebug("Float.encode: " + fv.getFloat()); - byte[] encoded = ByteHelper.floatToByteArray(fv.getFloat()); - CodecBuffer res = new CodecBuffer(); - res.setBits(encoded, encoded.length * Byte.SIZE); - - return res; - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Hexstring.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Hexstring.java deleted file mode 100644 index 62c0b080862bfa6e9d90ff6a8ba1b9d82e5d715d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Hexstring.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Integer.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Integer.java deleted file mode 100644 index 7faab3d099147b69d57d71b6c77bb60c3390672d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Integer.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import java.math.BigInteger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Integer extends ICodec { - - protected final static Pattern UNSIGNED_VARIANT = Pattern.compile("\\w*unsigned\\w*|UInt"); - - public Integer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - //TERFactory.getInstance().logDebug(">>> Integer.decode: " + decodingHypothesis.getName()); - - IntegerValue iv = null; - int lengthInBits; - byte[] value = null; - - // Get length - String hint = mainCodec.getHint(decodingHypothesis.getName() + "Len"); - if(hint == null) { - if (decodingHypothesis.getTypeEncodingVariant() == null) { - lengthInBits = getVariantBitLength(decodingHypothesis.getName()); // TCT3 - } else { - lengthInBits = getVariantBitLength(decodingHypothesis.getTypeEncodingVariant()); - } - } - else { - lengthInBits = java.lang.Integer.parseInt(hint); - } - - value = buf.readBits(lengthInBits); - - try { - hint = mainCodec.getHint(decodingHypothesis.getName() + "Sign"); - Matcher matcher; - if (hint==null) { - matcher = UNSIGNED_VARIANT.matcher(decodingHypothesis.getTypeEncodingVariant()); - } - else { - matcher = UNSIGNED_VARIANT.matcher(hint); - } - if(matcher.find()) { - // Unsigned integer - if(lengthInBits >= java.lang.Integer.SIZE) { - iv = mainCodec.getTciCDRequired().setInteger(new BigInteger(1, value)); - } - else { - iv = mainCodec.getTciCDRequired().setInteger(ByteHelper.byteArrayToInt(value)); - } - } - else { - // Signed integer - iv = mainCodec.getTciCDRequired().setInteger(ByteHelper.byteArrayToSignedInt(value, lengthInBits)); - } - } - catch(Exception e) { -// TERFactory.getInstance().logDebug("Integer.encode: " + decodingHypothesis.getTypeEncoding() + ", " + decodingHypothesis.getTypeEncodingVariant()); - // Assume unsigned integer - if(lengthInBits >= java.lang.Integer.SIZE) { - iv = mainCodec.getTciCDRequired().setInteger(new BigInteger(1, value)); - } - else { - iv = mainCodec.getTciCDRequired().setInteger(ByteHelper.byteArrayToInt(value)); - } // else, empty on purpose - } - - return iv; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> Integer.encode: " + value.getType().getName()); - - IntegerValue iv = (IntegerValue)value; - byte[] encoded = null; - CodecBuffer res = new CodecBuffer(); - int lengthInBits = 0; - int lengthInBytes = 0; - - // Get length - String hint = mainCodec.getHint(value.getType().getName() + "Len"); - if(hint == null) { -// TERFactory.getInstance().logDebug("Integer.encode: " + value.getValueEncodingVariant() + ", " + value.getValueEncoding()); -// TERFactory.getInstance().logDebug("Integer.encode: " + value.getType().getTypeEncodingVariant() + ", " + value.getType().getTypeEncoding()); - if (value.getType().getTypeEncodingVariant() != null) { - lengthInBits = getVariantBitLength(value.getType().getTypeEncodingVariant()); - } else { - lengthInBits = getVariantBitLength(value.getType().getName()); // TCT3 - } - } - else { - lengthInBits = java.lang.Integer.parseInt(hint); - } - lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - -// TERFactory.getInstance().logDebug(String.format("Integer.encode: length: %d", lengthInBytes)); - if (lengthInBits > java.lang.Integer.SIZE) { - encoded = ByteHelper.longToByteArray(mainCodec.getTciCDRequired().getBigInteger(iv), lengthInBytes); - } else { - encoded = ByteHelper.intToByteArray(mainCodec.getTciCDRequired().getInteger(iv), lengthInBytes); - } - res.setBits(encoded, lengthInBits); - - return res; - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Octetstring.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Octetstring.java deleted file mode 100644 index e03770124b7bc93ac972d688bdf65b503eabe9e6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Octetstring.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Octetstring extends ICodec { - - public Octetstring(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> Octetstring.decode: " + decodingHypothesis.getName()); - - OctetstringValue ov = (OctetstringValue)decodingHypothesis.newInstance(); - byte[] value = null; - int lengthInBytes = 0; - - // Get length - String hint = mainCodec.getHint(decodingHypothesis.getName() + "Len"); - if(hint == null) { - lengthInBytes = getEncodingLength(decodingHypothesis.getTypeEncoding()); - if (lengthInBytes == 0) { -// TERFactory.getInstance().logDebug("Octetstring.decode: Decode full buffer"); - lengthInBytes = buf.getNbBytes(); - } - } - else { - lengthInBytes = java.lang.Integer.parseInt(hint); - } - - value = buf.readBytes(lengthInBytes); - ov.setLength(lengthInBytes); - for(int i=0; i < value.length; i++) { - ov.setOctet(i, value[i]); - } - - return ov; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> Octetstring.encode: " + value.getType().getName()); - - OctetstringValue ov = (OctetstringValue)value; - byte[] encoded = new byte[ov.getLength()]; - - for(int i=0; i < ov.getLength(); i++) { - encoded[i] = (byte)ov.getOctet(i); - } - - return new CodecBuffer(encoded); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Record.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Record.java deleted file mode 100644 index 282f6aa2f178987c544824e707a2516fd3bd29d6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Record.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.adapter.TERFactory; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Record extends ICodec { - - public Record(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - RecordValue rv = (RecordValue)decodingHypothesis.newInstance(); - String[] fields = rv.getFieldNames(); - - for(int i=0; i < fields.length; i++) { - Type fieldType = rv.getField(fields[i]).getType(); - preDecodeField(fields[i], buf, fieldType, rv); - - java.lang.Boolean presence = mainCodec.getPresenceHint(fields[i]); - if(presence != null && presence == false) { - rv.setFieldOmitted(fields[i]); - } - else { - Value fv = mainCodec.decode(buf, rv.getField(fields[i]).getType()); - if(fv == null) { - if(mainCodec.getHint(fields[i] + "IgnoreErrorOnOptionalField") != null) { - // Set to omit + warning if optional - //TERFactory.getInstance().logDebug("Unable to decode optional field '" + fields[i] + "'. Setting to 'omit'"); - rv.setFieldOmitted(fields[i]); - } - else { - return null; - } - } - else { - rv.setField(fields[i], fv); - } - } - postDecodeField(fields[i], buf, fieldType, rv); - } - return rv; - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for (int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - CodecBuffer fieldBuf = mainCodec.encode(fieldValue); - postEncodeField(fields[i], fieldBuf); - buf.append(fieldBuf); - } - } - - return buf; - } - - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - } - - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - } - - protected void postEncodeField(String fieldName, CodecBuffer buf) { - - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/RecordOf.java b/javasrc/codec/org/etsi/ttcn/codec/generic/RecordOf.java deleted file mode 100644 index b308fc4cfc3d4c32aa7513406dc0e3a02265bdba..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/RecordOf.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class RecordOf extends ICodec { - - public RecordOf(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> RecordOf.decode: " + decodingHypothesis.getName()); - - RecordOfValue rov = (RecordOfValue)decodingHypothesis.newInstance(); - String lenHint = mainCodec.getHint(decodingHypothesis.getName() + "Len"); - String moreHint = mainCodec.getHint(decodingHypothesis.getName() + "More"); - int length = 0; - - if(lenHint != null) { - length = java.lang.Integer.parseInt(lenHint); - - for(int i=0; i < length; i++) { - rov.appendField(mainCodec.decode(buf, rov.getElementType())); - } - } - else { - while(moreHint.equals("true")) { - rov.appendField(mainCodec.decode(buf, rov.getElementType())); - length++; - moreHint = mainCodec.getHint(decodingHypothesis.getName() + "More"); - } - } - - rov.setLength(length); - return rov; - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> RecordOf.encode: " + value.getType().getName()); - - RecordOfValue rov = (RecordOfValue)value; - CodecBuffer buf = new CodecBuffer(); - - for (int i=0; i < rov.getLength(); i++) { - Value fieldValue = rov.getField(i); - buf.append(mainCodec.encode(fieldValue)); - } - - return buf; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Set.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Set.java deleted file mode 100644 index 95b6786b6916707cd349b6d0036577b6fb365f13..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Set.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Set extends ICodec { - - public Set(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - RecordValue rv = (RecordValue)decodingHypothesis.newInstance(); - String[] fields = rv.getFieldNames(); - - for(int i=0; i < fields.length; i++) { - rv.setFieldOmitted(fields[i]); - } - return rv; - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for (int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - buf.append(mainCodec.encode(fieldValue)); - } - } - - return buf; - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/SetOf.java b/javasrc/codec/org/etsi/ttcn/codec/generic/SetOf.java deleted file mode 100644 index dc593fbf72ae5ac392e55437865235ae77b696c6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/SetOf.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Union.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Union.java deleted file mode 100644 index 981dc2098b0bdfd2c1d186889fef09f66e733768..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Union.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.etsi.ttcn.codec.generic; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.codec.ICodec; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -public class Union extends ICodec { - - public Union(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - UnionValue uv = (UnionValue)decodingHypothesis.newInstance(); - String variant = ""; - - variant = mainCodec.getHint(decodingHypothesis.getName()); - //TERFactory.getInstance().logDebug("Union: Looking for variant " + decodingHypothesis.getName() + "/" + variant); - - if(variant != null) { - Value value = uv.getVariant(variant); - if (value == null) { - value = mainCodec.getTciCDRequired().getUnionValue(decodingHypothesis, variant); - if (value != null) { - //TERFactory.getInstance().logDebug("Union (TCT3): " + value.getType().getName()); - uv.setVariant(variant, mainCodec.decode(buf, value.getType())); - return uv; - } - } else { - //TERFactory.getInstance().logDebug("Union (TTWB): " + value.getType().getName()); - uv.setVariant(variant, mainCodec.decode(buf, value.getType())); - return uv; - } - } - - // no hint. Try all variants... - String[] variants = uv.getVariantNames(); - for(int i=0; i < variants.length; i++) { - // Copy buf to preserve it in case of failure - CodecBuffer variantBuf = buf.getBuffer(0, buf.getNbBits()); - - // Try to decode this variant - Value vv = null; - Value value = uv.getVariant(variants[i]); - if (value == null) { - value = uv.getVariant(mainCodec.getHint(variants[i])); - if (value == null) { - value = mainCodec.getTciCDRequired().getUnionValue(decodingHypothesis, mainCodec.getHint(variants[i])); - if (value != null) { - //TERFactory.getInstance().logDebug("Union (TCT3): " + value.getType().getName()); - vv = mainCodec.decode(buf, value.getType()); - } - } else { - //TERFactory.getInstance().logDebug("Union (TTWB): " + value.getType().getName()); - vv = mainCodec.decode(buf, value.getType()); - } - } else { - vv = mainCodec.decode(buf, value.getType()); - } - if(vv != null) { - buf.overwriteWith(variantBuf); - uv.setVariant(variants[i], vv); - return uv; - } - } - return null; - } - - @Override - public CodecBuffer encode(Value value) { - - UnionValue uv = (UnionValue)value; - - CodecBuffer buf = new CodecBuffer(); - preEncode(buf, uv); - CodecBuffer variantBuf = mainCodec.encode(uv.getVariant(uv.getPresentVariantName())); - buf.append(variantBuf); - - return buf; - } - - protected void preEncode(CodecBuffer buf, UnionValue uv) { - - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/UniversalCharstring.java b/javasrc/codec/org/etsi/ttcn/codec/generic/UniversalCharstring.java deleted file mode 100644 index 62c0b080862bfa6e9d90ff6a8ba1b9d82e5d715d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/UniversalCharstring.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ diff --git a/javasrc/codec/org/etsi/ttcn/codec/generic/Verdict.java b/javasrc/codec/org/etsi/ttcn/codec/generic/Verdict.java deleted file mode 100644 index 62c0b080862bfa6e9d90ff6a8ba1b9d82e5d715d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/generic/Verdict.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/AnyIcmpv6Message.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/AnyIcmpv6Message.java deleted file mode 100644 index 2d9656422ae16f7390d59c11eee9f4dd5770d2e8..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/AnyIcmpv6Message.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; - -import org.etsi.common.ByteHelper; - -public class AnyIcmpv6Message extends Record implements IMarkerCallback { - - public AnyIcmpv6Message(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("data")) { - mainCodec.setHint("octetstringLen", Integer.toString(buf.getNbBytes())); - } - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { - - if(fieldName.equals("checksum")) { - buf.setMarker("zchecksum", 0, this); - } - } - - @Override - public void run(String markerName, CodecBuffer left, CodecBuffer right) { - - if(markerName.equals("zchecksum")) { - - int checksum = 0; - byte[] src = left.getBits("sourceAddress", 128); - byte[] dst = left.getBits("destinationAddress", 128); - byte[] nh = ByteHelper.intToByteArray(java.lang.Integer.parseInt(mainCodec.getHint("Ipv6NextHeader")), 2); - byte[] pl = ByteHelper.intToByteArray(java.lang.Integer.parseInt(mainCodec.getHint("payloadLength")), 2); - - byte[] pseudo = ByteHelper.concat(src, dst, pl, nh); - byte[] payload = ByteHelper.concat(left.getBits(left.getNbBits() - 16, 16), right.getBits()); - - byte[] all = ByteHelper.concat(pseudo, payload, new byte[]{(byte)0x00}); - - for(int i=0; i < (all.length - 1); i+=2) { - checksum += ((all[i] & 0x000000ff) << 8) + (all[i+1] & 0x000000ff); - checksum = ((checksum >> 16) & 0x0000ffff) + (checksum & 0x0000ffff); - } - - checksum = (~ checksum) & 0x0000ffff; - - CodecBuffer preserveRight = right.getBuffer(16, right.getNbBits() - 16); - right.setBytes(ByteHelper.intToByteArray(checksum, 2)); - right.append(preserveRight); - } - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/ExtensionHeader.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/ExtensionHeader.java deleted file mode 100644 index 8c7e776c9c6982893ad3fec6b487fed15487172e..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/ExtensionHeader.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class ExtensionHeader extends Union { - - public ExtensionHeader(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - String nhHint = mainCodec.getHint("Ipv6NextHeader"); - String extHdr = ""; - - if(nhHint != null) { - int nh = Integer.parseInt(nhHint); - switch(nh) { - case 0: - extHdr = "hopByHopHeader"; - break; - case 43: - extHdr = "routingHeader"; - break; - case 44: - extHdr = "fragmentHeader"; - break; - case 60: - extHdr = "destinationOptionHeader"; - break; - case 41: - extHdr = "tunnelIPv6"; - break; - default: - extHdr = "otherHeader"; - } - } - mainCodec.setHint("ExtensionHeader", extHdr); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Icmpv6Message.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/Icmpv6Message.java deleted file mode 100644 index 6e3389cf1f6c2165382802fc37a8e2752ff5ba8e..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Icmpv6Message.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Icmpv6Message extends Union { - - public Icmpv6Message(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - int icmpType = 0x00FF & buf.getBytes(0, 1)[0]; - String icmpMsg = ""; - - switch(icmpType) { - case 144: - icmpMsg = "homeAgentAddressDiscoveryRequest"; - break; - case 145: - icmpMsg = "homeAgentAddressDiscoveryReply"; - break; - case 146: - icmpMsg = "mobilePrefixSolicitation"; - break; - case 147: - icmpMsg = "mobilePrefixAdvertisement"; - break; - case 133: - icmpMsg = "routerSolicitation"; - break; - case 134: - icmpMsg = "routerAdvertisement"; - icmpMsg = "mipRouterAdvertisement"; - break; - case 135: - icmpMsg = "neighborSolicitation"; - break; - case 136: - icmpMsg = "neighborAdvertisement"; - break; - case 137: - icmpMsg = "redirect"; - break; - case 138: - icmpMsg = "routerRenumbering"; - break; - case 1: - icmpMsg = "destinationUnreachable"; - break; - case 2: - icmpMsg = "packetTooBig"; - break; - case 3: - icmpMsg = "timeExceeded"; - break; - case 4: - icmpMsg = "parameterProblem"; - break; - case 128: - icmpMsg = "echoRequest"; - break; - case 129: - icmpMsg = "echoReply"; - break; - default: - icmpMsg = "other"; - } - - mainCodec.setHint(decodingHypothesis.getName(), icmpMsg); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6ExtHdr.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6ExtHdr.java deleted file mode 100644 index 02d0bca443953b9c0f23eef1ac7321fc6165b9a7..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6ExtHdr.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -import org.etsi.common.ByteHelper; - -public class Ipv6ExtHdr extends Record { - - public Ipv6ExtHdr(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("data")) { - mainCodec.setHint("octetstringLen", mainCodec.getHint("Ipv6ExtHdrLen")); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("hdrLen")) { -// int len = ((IntegerValue)(rv.getField(fieldName))).getInteger(); TTWB iterface is getInt, TCI shall be getInteger - int len = mainCodec.getTciCDRequired().getInteger((IntegerValue)(rv.getField(fieldName))); - mainCodec.setHint("Ipv6ExtHdrLen", Integer.toString(len)); - } - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { - - if(fieldName.equals("nextHeader")) { - mainCodec.setHint("Ipv6NextHeader", Integer.toString(ByteHelper.byteArrayToInt(buf.getBytes(0, 1)))); - } - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Header.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Header.java deleted file mode 100644 index f88805ddb9c9db778c81fc835feec7a3e4df1e40..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Header.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; - -import org.etsi.common.ByteHelper; - -public class Ipv6Header extends Record implements IMarkerCallback { - - public Ipv6Header(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { - - if(fieldName.equals("payloadLength")) { - buf.setMarker(fieldName, 0, this); - } - - if(fieldName.equals("nextHeader")) { - mainCodec.setHint("Ipv6NextHeader", Integer.toString(ByteHelper.byteArrayToInt(buf.getBytes(0, 1)))); - } - - else if(fieldName.equals("sourceAddress")) { - buf.setMarker("sourceAddress", 0, null); - } - - else if(fieldName.equals("destinationAddress")) { - buf.setMarker("destinationAddress", 0, null); - } - - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - - if(markerName.equals("payloadLength")) { - int length = (rightBuf.getNbBits() - 288) / 8; - CodecBuffer preserveRightBuf = rightBuf.getBuffer(16, rightBuf.getNbBits() - 16); - rightBuf.setBytes(ByteHelper.intToByteArray(length, 2)); - rightBuf.append(preserveRightBuf); - mainCodec.setHint("payloadLength", Integer.toString(length)); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Payload.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Payload.java deleted file mode 100644 index b8e1c14d10e5c501aeaed8962dca5551cc768fc7..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Ipv6Payload.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class Ipv6Payload extends Union { - - public Ipv6Payload(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - - String nhHint = mainCodec.getHint("Ipv6NextHeader"); - String extHdr = ""; - - if(nhHint != null) { - int nh = Integer.parseInt(nhHint); - switch(nh) { - case 58: - extHdr = "icmpv6"; - break; - case 6: - extHdr = "tcp"; - break; - case 17: - extHdr = "udp"; - break; - default: - extHdr = "other"; - } - } - mainCodec.setHint("Ipv6Payload", extHdr); - - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/ipv6/Plugin.java deleted file mode 100644 index 17dd05b2b9c0e8fd647452c3cbcc230eadde713c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/ipv6/Plugin.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.etsi.ttcn.codec.ipv6; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - - cf.setCodec(TciTypeClass.UNION, "IPv6", "ExtensionHeader", ExtensionHeader.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "OtherIpv6ExtHdr", Ipv6ExtHdr.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".otherHeader", Ipv6ExtHdr.class); - cf.setCodec(TciTypeClass.UNION, "IPv6", "Ipv6Payload", Ipv6Payload.class); - cf.setCodec(TciTypeClass.UNION, "IPv6", "Icmpv6Message", Icmpv6Message.class); - // cf.setCodec(TciTypeClass.UNION, "IPv6", ".icmpv6", Icmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "DestinationUnreachableMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".destinationUnreachable", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "PacketTooBigMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".packetTooBig", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "TimeExceededMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".timeExceeded", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "ParameterProblemMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".parameterProblem", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "EchoRequestMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".echoRequest", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "EchoReplyMessage", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".echoReply", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "OtherIcmpv6Message", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", ".other", AnyIcmpv6Message.class); - cf.setCodec(TciTypeClass.RECORD, "IPv6", "Ipv6Header", Ipv6Header.class); - - - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcEnableSecurity.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcEnableSecurity.java deleted file mode 100644 index 1cb61fa3332bd58c7dbc14527a10dc8495367b3a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcEnableSecurity.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class AcEnableSecurity extends Record { - - public AcEnableSecurity(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> AcEnableSecurity.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> AcEnableSecurity.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("certificateId")) { - mainCodec.setHint(decodingHypothesis.getName() + "Len", String.valueOf(buf.getNbBytes())); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> AcEnableSecurity.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class AcEnableSecurity diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcFsapPrimitive.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcFsapPrimitive.java deleted file mode 100644 index 084fe339a70da4b163594f51dba97ec28c631f6d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcFsapPrimitive.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.UnionValue; - -public class AcFsapPrimitive extends Union { - - public AcFsapPrimitive(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - String variant = uv.getPresentVariantName(); - int primitiveId = -1; - - // Append AcGnPrimitive message id - buf.appendBytes(ByteHelper.intToByteArray(2, 1)); // AdapterControl Primitive identifer for AcFsapPrimitive - - // Append primitive command identifier - if(variant.equals("inSapPrimitivesUp")) { - primitiveId = 0; - } - else if(variant.equals("stopTransmission")) { - primitiveId = 1; - } - buf.appendBytes(ByteHelper.intToByteArray(primitiveId, 1)); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnPrimitive.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnPrimitive.java deleted file mode 100644 index 5002d3b4d47ed285fd9d2b02dfe22ce1bef2af6a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnPrimitive.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.common.ByteHelper; - -public class AcGnPrimitive extends Union { - - public AcGnPrimitive(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - // Read message id (AcGnPrimitive) - if(0x00 != (0x00FF & buf.readBytes(1)[0])) { - return; - } - - // Read primitive id - int primitiveId = 0x00FF & buf.readBytes(1)[0]; - String primitive = ""; - - switch(primitiveId) { - case 0: - primitive = "startBeaconing"; - break; - case 1: - primitive = "stopBeaconing"; - break; - case 2: - primitive = "startPassBeaconing"; - break; - case 3: - primitive = "stopPassBeaconing"; - break; - case 4: - primitive = "startBeaconingMultipleNeighbour"; - break; - case 5: - primitive = "stopBeaconingMultipleNeighbour"; - break; - case 6: - primitive = "getLongPosVector"; - break; - } - - mainCodec.setHint(decodingHypothesis.getName(), primitive); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - String variant = uv.getPresentVariantName(); - int primitiveId = -1; - - // Append AcGnPrimitive message id - buf.appendBytes(ByteHelper.intToByteArray(0, 1)); - - // Append primitive id - if(variant.equals("startBeaconing")) { - primitiveId = 0; - } - else if(variant.equals("stopBeaconing")) { - primitiveId = 1; - } - else if(variant.equals("startPassBeaconing")) { - primitiveId = 2; - } - else if(variant.equals("stopPassBeaconing")) { - primitiveId = 3; - } - else if(variant.equals("startBeaconingMultipleNeighbour")) { - primitiveId = 4; - } - else if(variant.equals("stopBeaconingMultipleNeighbour")) { - primitiveId = 5; - } - else if(variant.equals("getLongPosVector")) { - primitiveId = 6; - } - buf.appendBytes(ByteHelper.intToByteArray(primitiveId, 1)); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnResponse.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnResponse.java deleted file mode 100644 index e70a81848bf42f24d25bb8ad570df3e474a3f192..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnResponse.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.adapter.TERFactory; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.common.ByteHelper; - -public class AcGnResponse extends Union { - - public AcGnResponse(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - // Read message id (AcGnResponse) - if(0x00 != (0x00FF & buf.readBytes(1)[0])) { - TERFactory.getInstance().logDebug("Bad hypothesis"); - return; - } - - // Read response id - int responseId = 0x00FF & buf.readBytes(1)[0]; - String variant = ""; - - switch(responseId) { - case 0: - variant = "failure"; - break; - case 6: - variant = "getLongPosVector"; - break; - } - - mainCodec.setHint(decodingHypothesis.getName(), variant); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - String variant = uv.getPresentVariantName(); - int responseId = -1; - - // Append AcGnResponse message id - buf.appendBytes(ByteHelper.intToByteArray(0, 1)); - - // Append response id - if(variant.equals("failure")) { - responseId = 0; - } - else if(variant.equals("getLongPosVector")) { - responseId = 6; - } - buf.appendBytes(ByteHelper.intToByteArray(responseId, 1)); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssAwaitDistanceCovered.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssAwaitDistanceCovered.java deleted file mode 100644 index 05151b8e81a3781f80955b64f7c4ea12ef02d839..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssAwaitDistanceCovered.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Boolean; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class AcGnssAwaitDistanceCovered extends Boolean { - - private static final int AcGnssDistanceCovered = 0x03; - - public AcGnssAwaitDistanceCovered(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - byte[] readId = buf.readBytes(1); - if(readId[0] != AcGnssDistanceCovered) { - return null; - } - - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - return new CodecBuffer(new byte[] {0x02}); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssPrimitive.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssPrimitive.java deleted file mode 100644 index 369d8a3049b4e2cc4b6648d01f8c86e3b94976a4..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssPrimitive.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.common.ByteHelper; - -public class AcGnssPrimitive extends Union { - - public AcGnssPrimitive(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - // Read message id (AcGnssPrimitive) - if(0x00 != (0x00FF & buf.readBytes(1)[0])) { - return; - } - - // Read primitive id - int primitiveId = 0x00FF & buf.readBytes(1)[0]; - String primitive = ""; - - switch(primitiveId) { - case 0x70: - primitive = "loadScenario"; - break; - case 0x71: - primitive = "startScenario"; - break; - case 0x72: - primitive = "stopScenario"; - break; - case 0x73: - primitive = "distanceToCover"; - break; - case 0x74: - primitive = "changeSpeed"; - break; - case 0x75: - primitive = "changeHeading"; - break; - case 0x76: - primitive = "timeInRunningScenario"; - break; - } - - mainCodec.setHint(decodingHypothesis.getName(), primitive); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - String variant = uv.getPresentVariantName(); - int primitiveId = -1; - - buf.appendBytes(ByteHelper.intToByteArray(2, 1)); - - // Append primitive id - if(variant.equals("loadScenario")) { - primitiveId = 0x70; - mainCodec.setHint("ScenarioLen", "16"); - } - else if(variant.equals("startScenario")) { - primitiveId = 0x71; - } - else if(variant.equals("stopScenario")) { - primitiveId = 0x72; - } - else if(variant.equals("distanceToCover")) { - primitiveId = 0x73; - } - else if(variant.equals("changeSpeed")) { - primitiveId = 0x74; - } - else if(variant.equals("changeHeading")) { - primitiveId = 0x75; - } - else if(variant.equals("timeInRunningScenario")) { - primitiveId = 0x76; - mainCodec.setHint("integerLen", "32"); - } - buf.appendBytes(ByteHelper.intToByteArray(primitiveId, 1)); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssResponse.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssResponse.java deleted file mode 100644 index f4b440de650d88f3274de9c50389134cd8d8705b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcGnssResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Boolean; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class AcGnssResponse extends Boolean { - - private static final int AcGnssResponse = 0x02; - - public AcGnssResponse(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - byte[] readId = buf.readBytes(1); - if(readId[0] != AcGnssResponse) { - return null; - } - - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - return new CodecBuffer(new byte[] {0x02}); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecPrimitive.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecPrimitive.java deleted file mode 100644 index d646b0671de3f682471a8db36bc6bc593bc598bf..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecPrimitive.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; - -public class AcSecPrimitive extends Union { - - public AcSecPrimitive(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - // Read message id (AcSecPrimitive) - if(0x00 != (0x00FF & buf.readBytes(1)[0])) { - return; - } - - // Read primitive id - int primitiveId = 0x00FF & buf.readBytes(1)[0]; - String primitive = ""; - - switch(primitiveId) { - case 0x7a: - primitive = "acEnableSecurity"; - break; - case 0x7b: - primitive = "acDisableSecurity"; - break; - } - - mainCodec.setHint(decodingHypothesis.getName(), primitive); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - String variant = uv.getPresentVariantName(); - int primitiveId = -1; - - // Append AcSecPrimitive message id - buf.appendBytes(ByteHelper.intToByteArray(3, 1)); - - // Append primitive id - if(variant.equals("acEnableSecurity")) { - primitiveId = 0x7a; - mainCodec.setHint("ScenarioLen", "16"); - } - else if(variant.equals("acDisableSecurity")) { - primitiveId = 0x7b; - } - buf.appendBytes(ByteHelper.intToByteArray(primitiveId, 1)); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecResponse.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecResponse.java deleted file mode 100644 index 24e5501a16ae5ac35dc6ad4c29c5b9035ea006cb..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/AcSecResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Boolean; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class AcSecResponse extends Boolean { - - private static final int AcSecResponse = 0x05; - - public AcSecResponse(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - byte[] readId = buf.readBytes(1); - if(readId[0] != AcSecResponse) { - return null; - } - - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - return new CodecBuffer(new byte[] {0x02}); - } - -} // End of class AcSecResponse diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/adapter/Plugin.java deleted file mode 100644 index fdb3cc20d63207f51305ede951e52a33f016c293..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/adapter/Plugin.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.adapter; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "AdapterControl", "AcEnableSecurity", AcEnableSecurity.class); - cf.setCodec(TciTypeClass.UNION, "AdapterControl", "AcGnPrimitive", AcGnPrimitive.class); - cf.setCodec(TciTypeClass.UNION, "AdapterControl", "AcGnResponse", AcGnResponse.class); - cf.setCodec(TciTypeClass.UNION, "AdapterControl", "AcFsapPrimitive", AcFsapPrimitive.class); - cf.setCodec(TciTypeClass.UNION, "AdapterControl", "AcGnssPrimitive", AcGnssPrimitive.class); - cf.setCodec(TciTypeClass.BOOLEAN, "AdapterControl", "AcGnssResponse", AcGnssResponse.class); - cf.setCodec(TciTypeClass.UNION, "AdapterControl", "AcSecPrimitive", AcSecPrimitive.class); - cf.setCodec(TciTypeClass.BOOLEAN, "AdapterControl", "AcSecResponse", AcSecResponse.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpHeader.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpHeader.java deleted file mode 100644 index c24cf7d8dc37b116778283aa762686e9690242c9..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpHeader.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; - -public class BtpHeader extends Union { - - private static final String BTP_A_HEADER = "btpAHeader"; - private static final String BTP_B_HEADER = "btpBHeader"; - - public BtpHeader(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("BtpPortIdLen", "16"); - mainCodec.setHint("BtpPortInfo", "16"); - } - - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { - //FIXME to support BTP standalone we need to know for GN later if it is BTP A or BTP B - boolean isIncludedInGn = false; - StackTraceElement[] stackTrace = new Exception().getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) { - String className = stackTraceElement.getClassName(); - String methodName = stackTraceElement.getMethodName(); - if (className.contains("GeoNetworkingPacket") || className.contains("GnNonSecuredPacket") || methodName.contains("encvalue")) { - isIncludedInGn = true; - break; - } - } - if (!isIncludedInGn) { - String variant = uv.getPresentVariantName(); - if (variant.equals(BTP_A_HEADER)) { - buf.appendBytes(new byte[] {0x1}); - } - else if (variant.equals(BTP_B_HEADER)) { - buf.appendBytes(new byte[] {0x2}); - } - else { - buf.appendBytes(new byte[] {0x0}); - } - } - super.preEncode(buf, uv); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - String nhHint = mainCodec.getHint("GnNextHeader"); - String variant = BTP_B_HEADER; - - int nh; - if(nhHint != null) { - nh = Integer.parseInt(nhHint); - } - else { - byte[] result = buf.readBytes(1); - nh = result[0]; - } - switch (nh) { - case 1: - variant = BTP_A_HEADER; - break; - case 2: - variant = BTP_B_HEADER; - break; - default: - variant = BTP_B_HEADER; - } - mainCodec.setHint(decodingHypothesis.getName(), variant); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpPacket.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpPacket.java deleted file mode 100644 index 77318820a5a63fa69b94849750b3a4c089c5b396..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/BtpPacket.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class BtpPacket extends Record { - - public BtpPacket(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("BtpPortIdLen", "16"); - mainCodec.setHint("BtpPortInfoLen", "16"); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> BtpPacket.preDecodeField: " + fieldName + ", " + decodingHypothesis); - - if(fieldName.equals("payload")) { - if (buf.getNbBytes() == 0) { - mainCodec.setPresenceHint(fieldName, false); - } - } - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/DecodedBtpPayload.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/DecodedBtpPayload.java deleted file mode 100644 index 6e876bdd44195bb21593f00dcaae2b4a2ac00080..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/DecodedBtpPayload.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; - -public class DecodedBtpPayload extends Union { - - public DecodedBtpPayload(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { // See LibItsBtp_TypesAndValues TTCN-3 module - mainCodec.setHint("camPacket", "camPacket"); - mainCodec.setHint("denmPacket", "denmPacket"); - mainCodec.setHint("mapemPacket", "mapemPacket"); - mainCodec.setHint("spatemPacket", "spatemPacket"); - mainCodec.setHint("ivimPacket", "ivimPacket"); - mainCodec.setHint("evcsnPacket", "evcsnPacket"); - mainCodec.setHint("sremPacket", "sremPacket"); - mainCodec.setHint("ssemPacket", "ssemPacket"); - } - -} // End of class DecodedBtpPayload diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/Payload.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/Payload.java deleted file mode 100644 index 281aa509b2436d6410d4e416b84a1eeeefc2b998..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/Payload.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class Payload extends Record { - - public Payload(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("decodedPayload")) { - mainCodec.setHint(fieldName + "IgnoreErrorOnOptionalField", "true"); - } - else if(fieldName.equals("rawPayload")) { - int pl = buf.getNbBytes(); - if (pl != 0) { - buf.overwriteWith(rawBuffer); - } else { - mainCodec.setPresenceHint(fieldName, false); - } - } - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - int pl = buf.getNbBytes(); - - // Save complete buf for 'rawPayload' - rawBuffer = buf.getBuffer(0, pl * 8); - } - - private CodecBuffer rawBuffer = null; -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/Plugin.java deleted file mode 100644 index 9bb2a34fb1db6ecdd8451e1723e70fd4676f1936..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/Plugin.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "LibItsBtp", "BtpPacket", BtpPacket.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsBtp", "BtpPayload", Payload.class); - cf.setCodec(TciTypeClass.UNION, "LibItsBtp", "BtpHeader", BtpHeader.class); - cf.setCodec(TciTypeClass.UNION, "LibItsBtp", "DecodedBtpPayload", DecodedBtpPayload.class); - cf.setCodec(TciTypeClass.UNION, "LibItsBtp", "UtBtpEvent", UtBtpEvent.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/btp/UtBtpEvent.java b/javasrc/codec/org/etsi/ttcn/codec/its/btp/UtBtpEvent.java deleted file mode 100644 index 5f8d292303209ee0e825806e2d6f05ffe6462b66..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/btp/UtBtpEvent.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.etsi.ttcn.codec.its.btp; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; - -public class UtBtpEvent extends Union { - - public UtBtpEvent(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("BtpPortIdLen", "16"); - mainCodec.setHint("BtpPortInfoLen", "16"); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/configtester/CfEvent.java b/javasrc/codec/org/etsi/ttcn/codec/its/configtester/CfEvent.java deleted file mode 100644 index 250b633e68fe06cf6e5f51717375ecff014dc92d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/configtester/CfEvent.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.etsi.ttcn.codec.its.configtester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Charstring; -import org.etsi.ttcn.tci.Type; - -public class CfEvent extends Charstring { - - public CfEvent(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - // Set Length for CfEvent - mainCodec.setHint("CfEventLen", new Integer(buf.getNbBytes()).toString()); - - return; - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/configtester/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/configtester/Plugin.java deleted file mode 100644 index 951f1bcdcd2faf17822e5c19a36f31e99f972366..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/configtester/Plugin.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @author ETSI / STF517 / Yann garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.configtester; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.generic.Boolean; - -public class Plugin { - - public static void init() { - // Basics - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "ConfigTester", "", Record.class); - cf.setCodec(TciTypeClass.BOOLEAN, "ConfigTester", "", Boolean.class); - cf.setCodec(TciTypeClass.CHARSTRING, "ConfigTester", "", CfEvent.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/facilities/FacilitiesInd.java b/javasrc/codec/org/etsi/ttcn/codec/its/facilities/FacilitiesInd.java deleted file mode 100644 index 5d2e7a1bcb662cd1732b4c744436dd53781bdd2c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/facilities/FacilitiesInd.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.facilities; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class FacilitiesInd extends Record { - - public FacilitiesInd(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> FacilitiesInd.preDecode: " + decodingHypothesis); - - int msgLen = buf.getNbBits() - 8 - 8 - 8 - 32 - 8 - 16 - 16 - 256 - 32; // FIXME Add support of SSP (Bit256) & ITS-AID (UInt32) extra fields: fixed size (256) is not nice! - int offset = 0; - - messageBuffer = buf.getBuffer(offset, msgLen); offset += msgLen; - gnNh = buf.getBuffer(offset, 8); offset += 8; - gnHt = buf.getBuffer(offset, 8); offset += 8; - gnHst = buf.getBuffer(offset, 8); offset += 8; - gnLifetime = buf.getBuffer(offset, 32); offset += 32; - gnTc = buf.getBuffer(offset, 8); offset += 8; - btpDestinationPort = buf.getBuffer(offset, 16); offset += 16; - btpInfo = buf.getBuffer(offset, 16); offset += 16; - ssp = buf.getBuffer(offset, 256); offset += 256; - its_aid = buf.getBuffer(offset, 32); offset += 32; - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> FacilitiesInd.preDecodeField: " + fieldName + " - " + decodingHypothesis); - - if(fieldName.equals("gnNextHeader")) { - buf.overwriteWith(gnNh); - } - else if(fieldName.equals("gnHeaderType")) { - buf.overwriteWith(gnHt); - } - else if(fieldName.equals("gnHeaderSubtype")) { - buf.overwriteWith(gnHst); - } - else if(fieldName.equals("gnLifetime")) { - buf.overwriteWith(gnLifetime); - } - else if(fieldName.equals("gnTrafficClass")) { - buf.overwriteWith(gnTc); - } - else if(fieldName.equals("btpDestinationPort")) { - buf.overwriteWith(btpDestinationPort); - } - else if(fieldName.equals("btpInfo")) { - buf.overwriteWith(btpInfo); - } - else if(fieldName.equals("ssp")) { - buf.overwriteWith(ssp); - } - else if(fieldName.equals("its_aid")) { - buf.overwriteWith(its_aid); - } - else { - buf.overwriteWith(messageBuffer); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - } - - @Override - public CodecBuffer encode(Value value) { - - return super.encode(value); - } - - private CodecBuffer messageBuffer = null; - private CodecBuffer gnNh = null; - private CodecBuffer gnHt = null; - private CodecBuffer gnHst = null; - private CodecBuffer gnLifetime = null; - private CodecBuffer gnTc = null; - private CodecBuffer btpDestinationPort = null; - private CodecBuffer btpInfo = null; - private CodecBuffer ssp = null; - private CodecBuffer its_aid = null; -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/facilities/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/facilities/Plugin.java deleted file mode 100644 index acd62ee1b2cb61cda016928515cadbd2c9e40f86..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/facilities/Plugin.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @author ETSI / STF484 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.facilities; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "CamInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "DenmInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "MapemInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "SpatemInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "IvimInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "EvcsnInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "SremInd", FacilitiesInd.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "SsemInd", FacilitiesInd.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/BasicHeader.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/BasicHeader.java deleted file mode 100644 index cc49f737b09acc12ad1d8208e5f851eeeb3c0e90..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/BasicHeader.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class BasicHeader extends Record { - - public BasicHeader(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("LtBaseLen", "2"); - mainCodec.setHint("BasicNextHeaderLen", "4"); - mainCodec.setHint("HeaderTypeLen", "4"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> BasicHeader.postEncodeField: " + fieldName); - - if(fieldName.equals("nextHeader")) { - mainCodec.setHint("GnNextHeader", Integer.toString(buf.getBytes(buf.getNbBytes() - 1, 1)[0])); - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> BasicHeader.preDecodeField: " + fieldName + ", " + decodingHypothesis); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> BasicHeader.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - if(fieldName.equals("nextHeader")) { - int nh = ((EnumeratedValue)(rv.getField(fieldName))).getInt(); - mainCodec.setHint("GnNextHeader", Integer.toString(nh)); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/CommonHeader.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/CommonHeader.java deleted file mode 100644 index c45cc5ec0cd4cbf417fd2f5f2aa124525333dfa5..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/CommonHeader.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; - -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; - -public class CommonHeader extends Record implements IMarkerCallback { - - public CommonHeader(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("HeaderTypeLen", "4"); - mainCodec.setHint("NextHeaderLen", "4"); - mainCodec.setHint("Bit8Len", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> CommonHeader.postEncodeField: " + fieldName); - - if(fieldName.equals("nextHeader")) { - int nh = buf.getBits(buf.getNbBits() - 4, 4)[0]; - mainCodec.setHint("NextHeader", Integer.toString(nh)); - } else if(fieldName.equals("plLength")) { - buf.setMarker("plLength", 0, this); - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> CommonHeader.preDecodeField: " + fieldName + ", " + decodingHypothesis); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> CommonHeader.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - if(fieldName.equals("nextHeader")) { - int nh = ((EnumeratedValue)(rv.getField(fieldName))).getInt(); - mainCodec.setHint("GnNextHeader", Integer.toString(nh)); - } - - else if(fieldName.equals("headerTST")) { - String headerTST = ((UnionValue)(rv.getField(fieldName))).getPresentVariantName(); - if (headerTST.equals("beaconHdr")) { - mainCodec.setHint("IsBeacon", "true"); - } - } - - else if(fieldName.equals("plLength")) { -// int pl = ((IntegerValue)(rv.getField(fieldName))).getInteger(); TTWB iterface is getInt, TCI shall be getInteger - int pl = mainCodec.getTciCDRequired().getInteger((IntegerValue)(rv.getField(fieldName))); - mainCodec.setHint("payloadLength", Integer.toString(pl)); - } - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { -// TERFactory.getInstance().logDebug(">>> CommonHeader.run"); - - if(markerName.equals("plLength")) { - int pl = java.lang.Integer.parseInt(mainCodec.getHint("payloadLength")); - CodecBuffer preserveRightBuf = rightBuf.getBuffer(16, rightBuf.getNbBits() - 16); - rightBuf.setBytes(ByteHelper.intToByteArray(pl, 2)); - rightBuf.append(preserveRightBuf); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GN_Address.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GN_Address.java deleted file mode 100644 index 55af58cf658f64ff0832fd50dade85e5c14d7500..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GN_Address.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class GN_Address extends Record { - - public GN_Address(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("TypeOfAddressLen", "1"); - mainCodec.setHint("StationTypeLen", "5"); - mainCodec.setHint("Oct6Len", "6"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> GN_Address.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GN_Address.preDecodeField: " + fieldName + ", " + decodingHypothesis); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GN_Address.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPacket.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPacket.java deleted file mode 100644 index c197645b59c4a46a2ee8e0f30cd5124153d60b8a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPacket.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class GeoNetworkingPacket extends Record { - - private boolean isSecuredMode = false; - - /** - * Used to decode the secured payload - */ - private Value packetValue; - - public GeoNetworkingPacket(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.encode: " + value); - - return super.encode(value); - } - - @Override - public CodecBuffer preEncode(Value value) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.preEncode: " + value); - - String gnNextHeader = mainCodec.getHint("GnNextHeader"); - isSecuredMode = (boolean)((gnNextHeader != null) && gnNextHeader.equals("32")); - - return new CodecBuffer(); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.postEncodeField: " + fieldName + ", " + isSecuredMode); - - if (isSecuredMode && fieldName.equals("packet")) { - // Ignore 'packet' encoding by reseting the CodecBuffer content - buf.overwriteWith(new CodecBuffer()); - } - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.decode: " + decodingHypothesis + ", " + isSecuredMode); - - packetValue = null; // Reset value - Value result = super.decode(buf, decodingHypothesis); // Normal decoding -// TERFactory.getInstance().logDebug("GeoNetworkingPacket.decode: Normal decoding=" + result); - if(isSecuredMode && (result != null)) { - // Override 'packet' field - RecordValue rv = (RecordValue) result; - rv.setField("packet", packetValue); - } - -// TERFactory.getInstance().logDebug("<<< GeoNetworkingPacket.decode: " + result); - return result; - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.preDecode: " + decodingHypothesis); - - String gnNextHeader = mainCodec.getHint("GnNextHeader"); - isSecuredMode = (boolean)((gnNextHeader != null) && gnNextHeader.equals("2")); -// TERFactory.getInstance().logDebug("GeoNetworkingPacket.preDecode: isSecuredMode=" + isSecuredMode); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.preDecodeField: " + fieldName + ", " + decodingHypothesis + ", " + isSecuredMode); - - if(isSecuredMode) { - if (fieldName.equals("packet")) { - mainCodec.setPresenceHint(fieldName, false); // Consider this field as omitted to skip decoding - } else if(fieldName.equals("securedMsg")) { - // Nothing to do - } - } else if(fieldName.equals("securedMsg")) { - mainCodec.setPresenceHint(fieldName, false); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPacket.postDecodeField: " + fieldName + ", " + rv); - - if(isSecuredMode) { - if(fieldName.equals("securedMsg")) { - RecordValue securedMsg = (RecordValue) rv.getField("securedMsg"); - RecordValue secPayload = (RecordValue) securedMsg.getField("payload_field"); - byte[] payload = new byte[]{}; - OctetstringValue ov = (OctetstringValue) secPayload.getField("data"); // See type record SecPayload - byte[] v = new byte[ov.getLength()]; - for (int j = 0; j < v.length; j++) { - v[j] = (byte) ov.getOctet(j); - } // End of 'for' statement - payload = ByteHelper.concat(payload, v); - - // Decode payload as GnNoSecured packet - packetValue = mainCodec.decode(new CodecBuffer(payload), rv.getField("packet").getType()); - } - } - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPdu.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPdu.java deleted file mode 100644 index 2740de956cb592dced0b17524a9c65c026e630fa..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GeoNetworkingPdu.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class GeoNetworkingPdu extends Record { - - public GeoNetworkingPdu(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPdu.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPdu.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GeoNetworkingPdu.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class GeoNetworkingPdu diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnIndReq.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnIndReq.java deleted file mode 100644 index 95bd460ddb21e1bc2a581f074511b3697eef0a61..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnIndReq.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class GnIndReq extends Record { - - public GnIndReq(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> GnIndReq.preDecode: " + decodingHypothesis); - - int msgLen = buf.getNbBits() - 48 - 256/*SSP*/ - 32/*ItsAid*/; - - messageBuffer = buf.getBuffer(0, msgLen); - macBuffer = buf.getBuffer(msgLen, 48); - msgLen += 48; - sspBuffer = buf.getBuffer(msgLen, 256/*SSP*/); - msgLen += 256/*SSP*/; - itsaidBuffer = buf.getBuffer(msgLen, 32/*ItsAid*/); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnIndReq.preDecodeField: " + fieldName + ", " + decodingHypothesis); - - if(fieldName.equals("macDestinationAddress")) { - buf.overwriteWith(macBuffer); - } else if(fieldName.equals("ssp")) { - buf.overwriteWith(sspBuffer); - } else if(fieldName.equals("its_aid")) { - buf.overwriteWith(itsaidBuffer); - } - else { - buf.overwriteWith(messageBuffer); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnIndReq.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug("GnIndReq.encode: " + value); - - return super.encode(value); - } - - private CodecBuffer messageBuffer = null; - private CodecBuffer macBuffer = null; - private CodecBuffer sspBuffer = null; - private CodecBuffer itsaidBuffer = null; -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnNonSecuredPacket.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnNonSecuredPacket.java deleted file mode 100644 index 7143f481650cd70da158278544e8d927d3ea5358..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/GnNonSecuredPacket.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class GnNonSecuredPacket extends Record { - - private static final byte c_protocolVersion = 0x02; - - public GnNonSecuredPacket(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.preDecode: " + decodingHypothesis); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.preDecodeField: " + fieldName + ", " + decodingHypothesis); - - // FIXME Yann if payload length is 0, why payload is not set to omit? -// if(fieldName.equals("payload")) { -// if (buf.getNbBytes() == 0) { -// mainCodec.setPresenceHint(fieldName, false); -// } -// } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.postEncodeField: " + fieldName); - - if(fieldName.equals("payload")) { - // Compute Payload's length and set a hint - int length = buf.getNbBits() / 8; - mainCodec.setHint("payloadLength", Integer.toString(length)); - } - } - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.encode: " + value); - - return super.encode(value); - } - - @Override - public CodecBuffer preEncode(Value value) { -// TERFactory.getInstance().logDebug(">>> GnNonSecuredPacket.preEncode: " + value); - - mainCodec.setHint("payloadLength", Integer.toString(0)); - return new CodecBuffer(); - } - -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/HeaderTST.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/HeaderTST.java deleted file mode 100644 index 2fbddd80c428040f23a5a3bf3a08a62eb17c30ef..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/HeaderTST.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.Type; - -public class HeaderTST extends Union { - - public HeaderTST(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> HeaderTST.preDecode: " + decodingHypothesis); - - int hdrType = 0x00FF & buf.getBits(0, 4)[0]; - String variant = ""; - String extHeader = ""; - - switch(hdrType) { - case 0: - variant = "anyHdr"; - extHeader = "anyHeader"; - break; - case 1: - variant = "beaconHdr"; - extHeader = "beaconHeader"; - break; - case 2: - variant = "geoUnicastHdr"; - extHeader = "geoUnicastHeader"; - break; - case 3: - variant = "geoAnycastHdr"; - extHeader = "geoAnycastHeader"; - break; - case 4: - variant = "geoBroadcastHdr"; - extHeader = "geoBroadcastHeader"; - break; - case 5: - variant = "tsbHdr"; - if((0x00FF & buf.getBits(4, 4)[0]) == 1) { - extHeader = "tsbHeader"; - } - else { - extHeader = "shbHeader"; - } - break; - case 6: - variant = "lsHdr"; - if((0x00FF & buf.getBits(4, 4)[0]) == 0) { - extHeader = "lsRequestHeader"; - } - else { - extHeader = "lsReplyHeader"; - } - break; - case 7: - variant = "saHdr"; - break; - default: - variant = "reserved"; - } - - mainCodec.setHint(decodingHypothesis.getName(), variant); - if(extHeader.equals("")) { - mainCodec.setPresenceHint("ExtendedHeader", false); - } - else { - mainCodec.setHint("ExtendedHeader", extHeader); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/LongPosVector.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/LongPosVector.java deleted file mode 100644 index 9aa048a1a2cb802b43f850ccf7c3b9e38af0f973..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/LongPosVector.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class LongPosVector extends Record { - - public LongPosVector(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Bit1Len", "1"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> LongPosVector.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> LongPosVector.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> LongPosVector.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class LongPosVector diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Payload.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Payload.java deleted file mode 100644 index df35fd6f7d3f20b8897a39f66af5ca88e968cf88..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Payload.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.adapter.TERFactory; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class Payload extends Record { - - public Payload(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - //TERFactory.getInstance().logDebug(">>> Payload.preDecode" + decodingHypothesis); - - if(fieldName.equals("decodedPayload")) { - String nhHint = mainCodec.getHint("GnNextHeader"); - String variant = ""; - - mainCodec.setHint(fieldName + "IgnoreErrorOnOptionalField", "true"); - - if(nhHint != null) { - int nh = Integer.parseInt(nhHint); - switch(nh) { - case 1: - case 2: - variant = "btpPacket"; - break; - case 3: - variant = "ipv6Packet"; - break; - default: - mainCodec.setPresenceHint("decodedPayload", false); - return; - } - } - mainCodec.setHint(decodingHypothesis.getName(), variant); - } - - else if(fieldName.equals("rawPayload")) { - buf.overwriteWith(rawBuffer); - mainCodec.setHint("GnRawPayloadLen", Integer.toString(buf.getNbBytes())); - } - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - //TERFactory.getInstance().logDebug(">>> Payload.preDecode: " + decodingHypothesis); - - // Sanity check on pl - int pl = java.lang.Integer.parseInt(mainCodec.getHint("payloadLength")); - int remainingBytesForPayload = buf.getNbBytes(); - - String hint = mainCodec.getHint("IsBeacon"); - if(pl != remainingBytesForPayload && hint==null) { - //TERFactory.getInstance().logDebug("Error: bad payload length or message truncated " + "(indicated: " + pl + " - real: " + remainingBytesForPayload + ")"); - pl = Math.min(remainingBytesForPayload, pl); - } - - // Save complete buf for 'rawPayload' - rawBuffer = buf.getBuffer(0, (remainingBytesForPayload) * 8); - } - - private CodecBuffer rawBuffer = null; -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Plugin.java deleted file mode 100644 index 45c03341ed6db8ec4eef51c5c24ea8085b61e086..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Plugin.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "BasicHeader", BasicHeader.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "TrafficClass", TrafficClass.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "LongPosVector", LongPosVector.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "GN_Address", GN_Address.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "CommonHeader", CommonHeader.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "GeoNetworkingPacket", GeoNetworkingPacket.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "GnNonSecuredPacket", GnNonSecuredPacket.class); - cf.setCodec(TciTypeClass.UNION, "LibItsGeoNetworking", "HeaderTST", HeaderTST.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsGeoNetworking", "Payload", Payload.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "GeoNetworkingInd", GnIndReq.class); - cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "GeoNetworkingReq", GnIndReq.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/TrafficClass.java b/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/TrafficClass.java deleted file mode 100644 index 42c1e430493ada07c90f0cd81680c1cdb5ee3f77..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/TrafficClass.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.etsi.ttcn.codec.its.geonetworking; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class TrafficClass extends Record { - - public TrafficClass(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SCFLen", "1"); - mainCodec.setHint("ChannelOffloadLen", "1"); - mainCodec.setHint("TcIdLen", "6"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> TrafficClass.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> TrafficClass.preDecodeField: " + fieldName + ", " + decodingHypothesis); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> TrafficClass.postDecodeField: " + fieldName + ", " + decodingHypothesis); - - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/MapSpatIndReq.java b/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/MapSpatIndReq.java deleted file mode 100644 index 210dd185df4c3aeeea5b12d92f3e4a8117be924d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/MapSpatIndReq.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.etsi.ttcn.codec.its.mapspat; - -// TODO To be removed -//import org.etsi.ttcn.codec.CodecBuffer; -//import org.etsi.ttcn.codec.MainCodec; -//import org.etsi.ttcn.codec.generic.Record; -//import org.etsi.ttcn.tci.RecordValue; -//import org.etsi.ttcn.tci.Type; -//import org.etsi.ttcn.tci.Value; - -//public class MapSpatIndReq extends Record { -// -// public MapSpatIndReq(MainCodec mainCodec) { -// super(mainCodec); -// } -// -// @Override -// protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -//// System.out.println(">>> MapSpatIndReq.preDecode: " + decodingHypothesis); -// -// int msgLen = buf.getNbBits() - 48; -// -// messageBuffer = buf.getBuffer(0, msgLen); -// macBuffer = buf.getBuffer(msgLen, 48); -// } -// -// @Override -// protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -//// System.out.println(">>> MapSpatIndReq.preDecodeField: " + fieldName + ", " + decodingHypothesis); -// -// if(fieldName.equals("macDestinationAddress")) { -// buf.overwriteWith(macBuffer); -// } -// else { -// buf.overwriteWith(messageBuffer); -// } -// } -// -// @Override -// protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -//// System.out.println(">>> MapSpatIndReq.postDecodeField: " + fieldName + ", " + decodingHypothesis); -// -// } -// -// @Override -// public CodecBuffer encode(Value value) { -//// System.out.println("MapSpatIndReq.encode: " + value); -// -// return super.encode(value); -// } -// -// private CodecBuffer messageBuffer = null; -// private CodecBuffer macBuffer = null; -//} // End of class MapSpatIndReq diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/Plugin.java deleted file mode 100644 index 931e075a71c016c20466ea66e80bfb304cd9cf78..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/mapspat/Plugin.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: https://forge.etsi.org/svn/ITS/branches/STF484_VALIDATION/javasrc/codec/org/etsi/ttcn/codec/its/geonetworking/Plugin.java $ - * $Id: Plugin.java 1834 2014-11-20 09:19:30Z berge $ - */ -package org.etsi.ttcn.codec.its.mapspat; - -//TODO To be removed -//import org.etsi.ttcn.tci.TciTypeClass; -//import org.etsi.ttcn.codec.CodecFactory; -// -//public class Plugin { -// -// public static void init() { -// -// CodecFactory cf = CodecFactory.getInstance(); -// cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "MapReq", MapSpatIndReq.class); -// cf.setCodec(TciTypeClass.RECORD, "LibIts_Interface", "SpatReq", MapSpatIndReq.class); -// } -//} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/AesCcm.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/AesCcm.java deleted file mode 100644 index dd0c1283e775ee5b005bfbe1302a45e5298f2533..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/AesCcm.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class AesCcm extends Record { - - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecdsa_nistp256_with_sha256 = 0x00; - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecies_nistp2561 = 0x01; - - public AesCcm(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SymmetricAlgorithmLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> AesCcm.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> AesCcm.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> AesCcm.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class AesCcm diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Certificate.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Certificate.java deleted file mode 100644 index e2a2ffe4dbb4d192faf3e9d6c6701be32824c967..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Certificate.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class Certificate extends Record { - - public Certificate(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> Certificate.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> Certificate.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> Certificate.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class Certificate \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/CertificateWithAlgo.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/CertificateWithAlgo.java deleted file mode 100644 index af2307cded12beda8cf9e70a43d0b5a0d55bdfdf..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/CertificateWithAlgo.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class CertificateWithAlgo extends Record { - - public CertificateWithAlgo(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> CertificateWithAlgo.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> CertificateWithAlgo.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> CertificateWithAlgo.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class CertificateWithAlgo diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/CircularRegion.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/CircularRegion.java deleted file mode 100644 index 83711c9c914f57a16febf0b740ddc293316757f0..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/CircularRegion.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; - -public class CircularRegion extends Record { // TODO To be removed - - public CircularRegion(MainCodec mainCodec) { - super(mainCodec); - } - -} // End of class CircularRegion \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Duration.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Duration.java deleted file mode 100644 index fe46041b93c9d796f5bc107ba6bba14bb059f738..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Duration.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class Duration extends Record { - - public Duration(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Bit3Len", "3"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> Duration.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> Duration.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> Duration.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class Duration \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/EccPoint.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/EccPoint.java deleted file mode 100644 index 6a7602bc60be31777ccfe4561e8559bd774ab13a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/EccPoint.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class EccPoint extends Record { - - final byte c_x_coordinate_only = 0x00; /** Only the x coordinate is encoded */ - final byte c_compressed_lsb_y_0 = 0x02; /** The point is compressed and y's least significant bit is zero */ - final byte c_compressed_lsb_y_1 = 0x03; /** The point is compressed and y's least significant bit is one */ - final byte c_uncompressed = 0x04; /** The y coordinate is encoded in the field y */ - - public EccPoint(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("EccPointTypeLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> EccPoint.postEncodeField: " + fieldName); - - if (fieldName.equals("type_")) { - // Store EccPointType value - mainCodec.setHint("EccPointType", Integer.toString(ByteHelper.byteArrayToInt(buf.getBytes(0, buf.getNbBytes())))); - } else if (fieldName.equals("x") || fieldName.equals("y")) { - // TODO Store first the octetstring length as specified in Draft ETSI TS 103 097 V1.1.14 Clause 4.2 - int type = Integer.parseInt(mainCodec.getHint("EccPointType")); - // TODO Check when octetsting length should be added -// if (type != c_uncompressed) { // Do not add length because of it is fixed to 32 -// CodecBuffer bufLen = new CodecBuffer(TlsHelper.getInstance().size2tls(buf.getNbBytes())); -// bufLen.append(buf); -// buf.overwriteWith(bufLen); -// } - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EccPoint.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type = buf.getBytes(0, 1)[0]; - // Store EccPointType value - mainCodec.setHint("EccPointType", Integer.toString(type)); - switch (type) { - case c_x_coordinate_only: - mainCodec.setPresenceHint("y", false); - break; - case c_compressed_lsb_y_0: - case c_compressed_lsb_y_1: - mainCodec.setPresenceHint("y", false); - break; - case c_uncompressed: - mainCodec.setPresenceHint("y", true); - mainCodec.setHint("EccPointContainer", "y"); // Set variant - break; - } // End of 'switch' statement - } else if (fieldName.equals("x")) { - int type = Integer.parseInt(mainCodec.getHint("EccPointType")); - int len = 32; - // TODO Check when octetsting length should be added -// if (type != c_uncompressed) { -// len = (int) TlsHelper.getInstance().tls2size(buf); -// } - mainCodec.setHint("octetstringLen", Integer.toString(len)); - } else if ((fieldName.equals("y") && mainCodec.getPresenceHint("y") == true)) { - int type = Integer.parseInt(mainCodec.getHint("EccPointType")); - int len = 32; - // TODO Check when octetsting length should be added -// if (type != c_uncompressed) { -// len = (int) TlsHelper.getInstance().tls2size(buf); -// } - mainCodec.setHint("octetstringLen", Integer.toString(len)); - mainCodec.setHint("EccPointContainer.yLen", Integer.toString(len)); // TCT3 Decoding EciesEncryptedKey, type became EccPointContainer.y - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EccPoint.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class EccPoint diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/EcdsaSignature.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/EcdsaSignature.java deleted file mode 100644 index ac5b030216a6a9b077ec82c9292684b2a92a0ce6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/EcdsaSignature.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -/** - * @desc Codec for ECDSA based signature - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.9 EcdsaSignature - */ -public class EcdsaSignature extends Record { - - final byte c_uncompressed = 0x04; /** The y coordinate is encoded in the field y */ - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public EcdsaSignature(MainCodec mainCodec) { - super(mainCodec); - } - - /** - * @desc Set the variant according to the EcdsaSignature type - * @see See Draft ETSI TS 103 097 V1.1.14 Clause 4.2.9 EcdsaSignature - */ - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> EcdsaSignature.postEncodeField: " + fieldName); - - if (fieldName.equals("s")) { - int type = Integer.parseInt(mainCodec.getHint("EccPointType")); - // TODO Store first the octetstring length as specified in Draft ETSI TS 103 097 V1.1.14 Clause 4.2 -// if (type != c_uncompressed) { // Do not add length because of it is fixed to 32 -// CodecBuffer bufLen = new CodecBuffer(TlsHelper.getInstance().size2tls(buf.getNbBytes())); -// bufLen.append(buf); -// buf.overwriteWith(bufLen); -// } - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EcdsaSignature.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("s")) { - int type = Integer.parseInt(mainCodec.getHint("EccPointType")); - int len = 32; - // TODO Store first the octetstring length as specified in Draft ETSI TS 103 097 V1.1.14 Clause 4.2 -// if (type != c_uncompressed) { -// len = (int) TlsHelper.getInstance().tls2size(buf); -// } - mainCodec.setHint("octetstringLen", Integer.toString(len)); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EcdsaSignature.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class EcdsaSignature \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/EciesEncryptedKey.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/EciesEncryptedKey.java deleted file mode 100644 index f48ac1a98a4ce40b65c12fb588ef2f39e3d18e5b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/EciesEncryptedKey.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class EciesEncryptedKey extends Record { - - final byte c_aes_128_ccm = 0x00; /** Symmetric key cryptography algorithm AES-CCM as specified in NIST SP 800-38C */ - - public EciesEncryptedKey(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Oct16Len", "16"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> EciesEncryptedKey.postEncodeField: " + fieldName); - - if (fieldName.equals("c")) { - int type = Integer.parseInt(mainCodec.getHint("SymmetricAlgorithm")); - if (type != c_aes_128_ccm) { // Do not add length because of it is fixed to 32 - CodecBuffer bufLen = new CodecBuffer(TlsHelper.getInstance().size2tls(buf.getNbBytes())); - bufLen.append(buf); - buf.overwriteWith(bufLen); - } - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EciesEncryptedKey.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("c")) { - int type = Integer.parseInt(mainCodec.getHint("SymmetricAlgorithm")); - int len = 32; - if (type != c_aes_128_ccm) { - len = (int) TlsHelper.getInstance().tls2size(buf); - } - mainCodec.setHint("octetstringLen", Integer.toString(len)); - } else if (fieldName.equals("t")) { - mainCodec.setHint("octetstringLen", "20"); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EciesEncryptedKey.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class EciesEncryptedKey \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParameters.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParameters.java deleted file mode 100644 index c2572bec060a3f7d78ed127ad49f16c888ed5ad5..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class EncryptionParameters extends Record { - - final byte c_aes_128_ccm = 0x00; /** Symmetric key cryptography algorithm AES-CCM as specified in NIST SP 800-38C */ - - public EncryptionParameters(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SymmetricAlgorithmLen", "8"); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> EncryptionParameters.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - if (fieldName.equals("symm_algorithm")) { - byte type_ = buf.getBytes(0, 1)[0]; - mainCodec.setHint("SymmetricAlgorithm", String.valueOf(type_)); - switch (type_) { - case (byte)c_aes_128_ccm: - mainCodec.setHint("EncryptionParametersContainer", "nonce"); // Set variant - break; - default: - mainCodec.setHint("EncryptionParametersContainer", "params"); // Set variant - } // End of 'switch' statement - } else { - if (mainCodec.getHint("EncryptionParametersContainer").equals("nonce")) { - mainCodec.setHint("octetstringLen", "12"); - mainCodec.setHint("EncryptionParametersContainer.nonceLen", "12"); // TCT3 Decoding HeaderFieldContainer.enc_params, the type nonce became EncryptionParametersContainer.nonce - } else { - int len = buf.readBits(Byte.SIZE)[0]; // field_sizeLen is 1 bytes - mainCodec.setHint("EncryptionParametersContainer.paramsLen", Integer.toString(len)); - } - } - } - -} // End of class EncryptionParameters \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParametersContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParametersContainer.java deleted file mode 100644 index f652531c669e9c5e870fd2e127f06c36553f835a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/EncryptionParametersContainer.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class EncryptionParametersContainer extends Union { - - public EncryptionParametersContainer(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Oct12Len", "12"); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> EncryptionParametersContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("params")) { - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class EncryptionParametersContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegion.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegion.java deleted file mode 100644 index 1f8783928a9d5307c4c80e5f455cec414d04f17b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegion.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class GeographicRegion extends Record { - - final byte c_none = 0x00; - final byte c_circle = 0x01; - final byte c_rectangle = 0x02; - final byte c_polygon = 0x03; - final byte c_id = 0x04; - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public GeographicRegion(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("RegionTypeLen", "8"); - } - - /** - * @desc Set the variant according to the GeographicRegion type - * @see See Draft ETSI TS 103 097 V1.1.14 Clause 5.7 TrailerFieldType - */ - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GeographicRegion.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - if (fieldName.equals("region_type")) { - byte type_ = buf.getBytes(0, 1)[0]; - mainCodec.setPresenceHint("region", true); - switch (type_) { - case (byte)c_circle: - mainCodec.setHint("GeographicRegionContainer", "circular_region"); // Set variant - break; - case (byte)c_rectangle: - mainCodec.setHint("GeographicRegionContainer", "rectangular_region"); // Set variant - break; - case (byte)c_polygon: - mainCodec.setHint("GeographicRegionContainer", "polygonal_region"); // Set variant - break; - case (byte)c_id: - mainCodec.setHint("GeographicRegionContainer", "id_region"); // Set variant - break; - case (byte)c_none: - mainCodec.setPresenceHint("region", false); - break; - default: - mainCodec.setHint("GeographicRegionContainer", "other_region"); // Set variant - break; - } // End of 'switch' statement - } - } - -} // End of class GeographicRegion \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegionContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegionContainer.java deleted file mode 100644 index 8502b8c726188e0c9809d885a70edeb395cecfb2..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/GeographicRegionContainer.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class GeographicRegionContainer extends Union { - - public GeographicRegionContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> GeographicRegionContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("other_region")) { - // FIXME Check for opaque length encoding depending of the length value : <= 127 or > 127 - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class GeographicRegionContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/GnSecurityInd.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/GnSecurityInd.java deleted file mode 100644 index be3aa102554981d9df387cd5f1a7a6940415f45a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/GnSecurityInd.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class GnSecurityInd extends Record { - - public GnSecurityInd(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnSecurityInd.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> GnSecurityInd.postDecode: " + decodingHypothesis.getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> GnSecurityInd.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class GnSecurityInd diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId3.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId3.java deleted file mode 100644 index c6251a87a88cab6f17d64e7f443712efe5082d2f..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId3.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Octetstring; -import org.etsi.ttcn.tci.Type; - -public class HashedId3 extends Octetstring { - - public HashedId3(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("HashedId3Len", "3"); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> HashedId3.preDecode: " + decodingHypothesis.getName()); - } - -} // End of class HashedId3 \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId8.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId8.java deleted file mode 100644 index f4e5bb0a923d411a0a14eef8e0229cfe5f7f2c83..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/HashedId8.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Octetstring; - -public class HashedId8 extends Octetstring { - - public HashedId8(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("HashedId8Len", "8"); - } - -} // End of class HashedId8 \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderField.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderField.java deleted file mode 100644 index 546805be0e0518f28390e95863a90714aa5f092c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderField.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -/** - * @desc Information of interest to the security layer - * @see Draft ETSI TS 103 097 V1.1.14 Clause 5.4 HeaderField - */ -public class HeaderField extends Record { - - final byte c_generation_time = 0x00; /** A timestamp of type Time64 */ - final byte c_generation_time_with_standard_deviation= 0x01; /** A timestamp of type Time64WithStandardDeviation */ - final byte c_expiration = 0x02; /** The point in time the validity of this message expires */ - final byte c_generation_location = 0x03; /** The location where this message was created */ - final byte c_request_unrecognized_certificate = 0x04; /** A request for certificates */ - final byte c_its_aid = 0x05; /** Its AID valued used to identify CAM/DENM secured messages */ - final byte c_signer_info = (byte)0x80; /** Information about the message's signer */ - final byte c_encryption_parameters = (byte)0x81; /** Information specific for certain recipients */ - final byte c_recipient_info = (byte)0x82; /** Additional parameters necessary for encryption purposes */ - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public HeaderField(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("HeaderFieldTypeLen", "8"); - mainCodec.setHint("Oct2Len", "2"); - } - - /** - * @desc Set the variant according to the HeaderField type - * @see See Draft ETSI TS 103 097 V1.1.14 Clause 5.5 HeaderFieldType - */ - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> HeaderField.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type_ = buf.getBytes(0, 1)[0]; - switch (type_) { - case (byte)c_generation_time: - mainCodec.setHint("HeaderFieldContainer", "generation_time"); // Set variant - break; - case (byte)c_generation_time_with_standard_deviation: - mainCodec.setHint("HeaderFieldContainer", "generation_time_with_standard_deviation"); // Set variant - break; - case (byte)c_expiration: - mainCodec.setHint("HeaderFieldContainer", "expiry_time"); // Set variant - break; - case (byte)c_generation_location: - mainCodec.setHint("HeaderFieldContainer", "generation_location"); // Set variant - break; - case (byte)c_request_unrecognized_certificate: - mainCodec.setHint("HeaderFieldContainer", "digests"); // Set variant - mainCodec.setHint("HashedId3Len", "3"); // FIXME TCT3 returns 12/length(3)/HashedId3 instead of 12/LibItsSecurity/HashedId3 - break; - case (byte)c_its_aid: - mainCodec.setHint("HeaderFieldContainer", "its_aid"); // Set variant - break; - case (byte)c_signer_info: - mainCodec.setHint("HeaderFieldContainer", "signer"); // Set variant - break; - case (byte)c_encryption_parameters: - mainCodec.setHint("HeaderFieldContainer", "enc_params"); // Set variant - break; - case (byte)c_recipient_info: - mainCodec.setHint("HeaderFieldContainer", "recipients"); // Set variant - break; - default: - mainCodec.setHint("HeaderFieldContainer", "other_header"); // Set variant - break; - } // End of 'switch' statement - } - } - -} // End of class HeaderField \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderFieldContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderFieldContainer.java deleted file mode 100644 index 71dd838b80f6659cce1cfa7e734362002d7e9c20..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/HeaderFieldContainer.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; - -/** - * @desc Container for the information of interest to the security layer - * @see Draft ETSI TS 103 097 V1.1.14 Clause 5.4 HeaderField - */ -public class HeaderFieldContainer extends Union { - - public HeaderFieldContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> HeaderFieldContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("other_header")) { - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> HeaderFieldContainer.preDecode: " + decodingHypothesis.getName()); - } - -} // End of class HeaderFieldContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/IdentifiedRegion.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/IdentifiedRegion.java deleted file mode 100644 index 6a5f5164216001ced282859378023223caf48ea7..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/IdentifiedRegion.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; - -public class IdentifiedRegion extends Record { - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public IdentifiedRegion(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("RegionDictionaryLen", "8"); - } - -} // End of class IdentifiedRegion \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/IntX.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/IntX.java deleted file mode 100644 index ca9a8e4a8fb765352cb1cb9b4de6589855615285..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/IntX.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Integer; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -/** - * @desc Codec for an integer of variable length - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.1 IntX - */ -public class IntX extends Integer { - - /** - * Specialised constructor - * @param mainCodec The MainCodec reference - */ - public IntX(MainCodec mainCodec) { - super(mainCodec); - } - - /** - * @desc Decoder for an integer of variable length - */ - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> IntX.decode: " + decodingHypothesis.getName()); - - // Read the first byte - byte msb = buf.getBytes(0, 1)[0]; - if ((msb & 0x80) == 0x00) { // Integer < 128 - mainCodec.setHint("IntXLen", "8"); - mainCodec.setHint("HeaderFieldContainer.its_aidLen", "8"); // TCT3 workaround, i don't know how to abstract this :-( - return super.decode(buf, decodingHypothesis); - } else { - // Decode the length. The encoding of the length shall use at most 7 bits set to 1 (see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.1 IntX) - byte bit; - byte byteLen = 1; - do { - bit = (byte) ((byte) (msb << byteLen++) & 0x80); - } while (bit != 0x00); - // Set the IntX length - mainCodec.setHint(decodingHypothesis.getName() + "Len", String.valueOf(byteLen * Byte.SIZE )); - mainCodec.setHint("HeaderFieldContainer.its_aid" + "Len", String.valueOf(byteLen * Byte.SIZE )); // TCT3 workaround, i don't know how to abstract this :-( - // Remove the length from the real integer value - byte[] newBuf = buf.getBytes(); - newBuf[0] &= (byte)(Math.pow(2.0, 8 - byteLen + 1) - 1); - CodecBuffer newBuffer = new CodecBuffer(newBuf); - buf.overwriteWith(newBuffer); - // Decode it - return super.decode(buf, decodingHypothesis); - } - } - - /** - * @desc Encoder for an integer of variable length - */ - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> IntX.encode: " + value.getType().getName()); - - int iv = mainCodec.getTciCDRequired().getInteger((IntegerValue)value); - byte[] result = TlsHelper.getInstance().size2tls(iv); - mainCodec.setHint("integerLen", String.valueOf(result.length * Byte.SIZE )); - IntegerValue newValue = mainCodec.getTciCDRequired().setInteger(ByteHelper.byteArrayToInt(result)); - return super.encode(newValue); - } - -} // End of class IntX diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ItsAidSsp.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ItsAidSsp.java deleted file mode 100644 index 9844279a1b5b08acd650e78cb898c3f7d691cdb9..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ItsAidSsp.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class ItsAidSsp extends Record { - - public ItsAidSsp(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> ItsAidSsp.postEncodeField: " + fieldName); - - if (fieldName.equals("service_specific_permissions")) { - CodecBuffer bufLen = new CodecBuffer(new byte[] { (byte)buf.getNbBytes() } ); -// TERFactory.getInstance().logDebug("ItsAidSsp.postEncodeField: bufLen = " + bufLen); - bufLen.append(buf); - buf.overwriteWith(bufLen); - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ItsAidSsp.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("service_specific_permissions")) { - int len = buf.readBits(Byte.SIZE)[0]; // FIXME Should be IntX? -// TERFactory.getInstance().logDebug("ItsAidSsp.preDecodeField: len=" + len); - if (mainCodec.getHint("ServiceSpecificPermissionsContainer").equals("sspCAM")) { - mainCodec.setHint("SspCAMLen", Integer.toString(len - 1/* Version byte*/)); - } else if (mainCodec.getHint("ServiceSpecificPermissionsContainer").equals("sspDENM")) { - mainCodec.setHint("SspDENMLen", Integer.toString(len -1/* Version byte*/)); - } else { - mainCodec.setHint("ServiceSpecificPermissionsContainer.opaqueLen", Integer.toString(len - 1/* Version byte*/)); - } - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ItsAidSsp.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("its_aid")) { - //int itsaid = ((IntegerValue)(rv.getField(fieldName))).getInt(); - int itsaid = mainCodec.getTciCDRequired().getInteger(((IntegerValue)(rv.getField(fieldName)))); - if (itsaid == 36) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspCAM"); - } else if (itsaid == 37) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspDENM"); - } else if (itsaid == 138) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - //mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspMAPEM"); - } else if (itsaid == 137) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - //mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspSPATEM"); - } else if (itsaid == 139) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - //mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspIVIM"); - } else if (itsaid == 140) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - //mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspSxEM"); - } else if (itsaid == 141) { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - //mainCodec.setHint("ServiceSpecificPermissionsContainer", "sspGnMgmt"); - } else { - mainCodec.setHint("ServiceSpecificPermissionsContainer", "opaque"); - } - } - } - -} // End of class ItsAidSsp diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Plugin.java deleted file mode 100644 index 9c24289c58827f341354a05ea38eeeb33bcc611c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Plugin.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecFactory; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.TciTypeClass; - -public class Plugin { - - public static void init() { - CodecFactory cf = CodecFactory.getInstance(); - // Draft ETSI TS 103 097 V1.1.14 Clause 4.2 Specification of basic format elements - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "PublicKey", PublicKey.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "EccPoint", EccPoint.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "AesCcm", AesCcm.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SignerInfo", SignerInfo.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "Signature", Signature.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "EcdsaSignature", EcdsaSignature.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "Time64WithStandardDeviation", Time64WithStandardDeviation.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "Duration", Duration.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "TwoDLocation", TwoDLocation.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ThreeDLocation", ThreeDLocation.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "EncryptionParameters", EncryptionParameters.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "GeographicRegion", GeographicRegion.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "CircularRegion", CircularRegion.class); - - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "SignerInfoContainer", SignerInfoContainer.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "EncryptionParametersContainer", EncryptionParametersContainer.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "GeographicRegionContainer", GeographicRegionContainer.class); - - cf.setCodec(TciTypeClass.ENUMERATED, "LibItsSecurity", "RegionDictionary", RegionDictionary.class); - - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "Time32", Time32.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "Time64", Time64.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "IntX", IntX.class); - - // Draft ETSI TS 103 097 V1.1.14 Clause 5 Specification of security header - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SecuredMessage", SecuredMessage.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "HeaderField", HeaderField.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SecPayload", SecPayload.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "TrailerField", TrailerField.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "RecipientInfo", RecipientInfo.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "EciesEncryptedKey", EciesEncryptedKey.class); - - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HeaderFields", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "IntXs", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HashedId3s", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "RecipientInfos", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "TrailerFields", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "RectangularRegions", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "PolygonalRegion", RecordOf.class); - // Change record of into set of in order to use superset - // record of shall be used, refer to ETSI TS 103 097 V 1.1.6 (2014-05) - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HeaderFields", RecordOf.class); - - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "PublicKeyContainer", Union.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "EccPointContainer", Union.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "SignatureContainer", Union.class); - - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "HeaderFieldContainer", HeaderFieldContainer.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "RecipientInfoContainer", RecipientInfoContainer.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "TrailerFieldContainer", TrailerFieldContainer.class); - - // Draft ETSI TS 103 097 V1.1.14 Clause 6 Specification of certificate format - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ToBeSignedCertificate", ToBeSignedCertificate.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "Certificate", Certificate.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectInfo", SubjectInfo.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectAssurance", SubjectAssurance.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectAttribute", SubjectAttribute.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ValidityRestriction", ValidityRestriction.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ItsAidSsp", ItsAidSsp.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ServiceSpecificPermissions", ServiceSpecificPermissions.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SspCAM", SspCAM.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SspDENM", SspDENM.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "CertificateWithAlgo", CertificateWithAlgo.class); - - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "SubjectAttributeContainer", SubjectAttributeContainer.class); - cf.setCodec(TciTypeClass.UNION, "LibItsSecurity", "ValidityRestrictionContainer", ValidityRestrictionContainer.class); - - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "CertificateChain", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "ValidityRestrictions", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "SubjectAttributes", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "ItsAidSsps", RecordOf.class); - // Change record of into set of in order to use superset - // record of shall be used, refer to ETSI TS 103 097 V 1.1.6 (2014-05) - - // TCT3 specific - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "PublicKeyContainer.eccPoint", EccPoint.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SignatureContainer.ecdsa_signature", EcdsaSignature.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "PublicKeyContainer.aesCcm", Signature.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "HeaderFieldContainer.signer", SignerInfo.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "EncryptionParametersContainer.public_key", EncryptionParameters.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "GeographicRegionContainer.circular_region", CircularRegion.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "GeographicRegionContainer.id_region", IdentifiedRegion.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "HeaderFieldContainer.generation_time_with_standard_deviation", HeaderField.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "HeaderFieldContainer.generation_location", HeaderField.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "HeaderFieldContainer.enc_params", EncryptionParameters.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "RecipientInfoContainer.enc_key", EciesEncryptedKey.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "RecipientInfoContainer.enc_key_other", RecipientInfoContainer.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "TrailerFieldContainer.signature_", Signature.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "TrailerFieldContainer.security_field", TrailerFieldContainer.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectAttributeContainer.key", PublicKey.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectAttributeContainer.rv", EccPoint.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "SubjectAttributeContainer.assurance_level", SubjectAssurance.class); - cf.setCodec(TciTypeClass.RECORD, "LibItsSecurity", "ValidityRestrictionContainer.region", GeographicRegion.class); - - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "HeaderFieldContainer.generation_time", Time64.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "HeaderFieldContainer.expiry_time", Time32.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "HeaderFieldContainer.its_aid", IntX.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "ItsAidSsp.its_aid", IntX.class); - cf.setCodec(TciTypeClass.INTEGER, "LibItsSecurity", "ValidityRestrictionContainer.end_validity", Time32.class); - - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "SignerInfoContainer.certificates", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "GeographicRegionContainer.rectangular_region", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "GeographicRegionContainer.polygonal_region", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HeaderFieldContainer.digests", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "HeaderFieldContainer.recipients", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "SubjectAttributeContainer.its_aid_list", RecordOf.class); - cf.setCodec(TciTypeClass.SET_OF, "LibItsSecurity", "SubjectAttributeContainer.its_aid_ssp_list", RecordOf.class); - // Change record of into set of in order to use superset - // record of shall be used, refer to ETSI TS 103 097 V 1.1.6 (2014-05) - - } -} // End of class Plugin \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/PublicKey.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/PublicKey.java deleted file mode 100644 index ce6b60c3129a952f1a28ddfd2311ae3b6da7564f..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/PublicKey.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class PublicKey extends Record { - - /** - * List of supported algorithms based on public key cryptography - */ - final byte c_ecdsa_nistp256_with_sha256 = 0x00; - /** - * List of supported algorithms based on public key cryptography - */ - final byte c_ecies_nistp2561 = 0x01; - - public PublicKey(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("PublicKeyAlgorithmLen", "8"); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> PublicKey.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("algorithm")) { - if (buf.getBytes(0, 1)[0] == c_ecdsa_nistp256_with_sha256) { - mainCodec.setHint("PublicKeyContainer", "eccPoint"); // Set variant - } else if (buf.getBytes(0, 1)[0] == c_ecies_nistp2561) { - mainCodec.setHint("PublicKeyContainer", "aesCcm"); // Set variant - } else { - mainCodec.setHint("PublicKeyContainer", "other_key"); // Set variant - } - } - } - -} // End of class PublicKey diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfo.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfo.java deleted file mode 100644 index 8671dcfebbf62f994aecaac39eaf87c198533f56..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfo.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class RecipientInfo extends Record { - - final byte c_ecies_nistp2561 = 0x01; /** List of supported algorithms based on public key cryptography */ - - public RecipientInfo(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("HashedId8Len", "8"); - mainCodec.setHint("PublicKeyAlgorithmLen", "8"); - mainCodec.setHint("Oct20Len", "20"); - } - - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> RecipientInfo.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("pk_encryption")) { - if (buf.getBytes(0, 1)[0] == c_ecies_nistp2561) { - mainCodec.setHint("RecipientInfoContainer", "enc_key"); // Set variant - } else { - mainCodec.setHint("RecipientInfoContainer", "enc_key_other"); // Set variant - } - } - } - - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> RecipientInfo.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> RecipientInfo.postEncodeField: " + fieldName); - } -} // End of class RecipientInfo \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfoContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfoContainer.java deleted file mode 100644 index a7ec0d5bb8c348455eca62b2832f05441e60c31f..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecipientInfoContainer.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class RecipientInfoContainer extends Union { - - public RecipientInfoContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> RecipientInfoContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("enc_key_other")) { - // FIXME Check for opaque length encoding depending of the length value : <= 127 or > 127 - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class RecipientInfoContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecordOf.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/RecordOf.java deleted file mode 100644 index 14466a857a3a64bbb4403562d9805291fb0a7299..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/RecordOf.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import java.util.ArrayList; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class RecordOf extends org.etsi.ttcn.codec.generic.RecordOf { - - public RecordOf(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { -// TERFactory.getInstance().logDebug(">>> security.RecordOf.decode: " + decodingHypothesis.getName()); - - int len = (int) TlsHelper.getInstance().tls2size(buf); -// TERFactory.getInstance().logDebug("security.RecordOf.decode: length=" + len); - if (len == 0) { - RecordOfValue rov = (RecordOfValue)decodingHypothesis.newInstance(); - rov.setLength(0); - return rov; - } - CodecBuffer newBuf = new CodecBuffer(buf.readBits(len * Byte.SIZE)); - - ArrayList recordOf = new ArrayList(); - RecordOfValue rov = (RecordOfValue)decodingHypothesis.newInstance(); - while (newBuf.getNbBits() != 0) { - recordOf.add(mainCodec.decode(newBuf, rov.getElementType())); -// TERFactory.getInstance().logDebug("security.RecordOf.decode: new len=" + newBuf.getNbBits() / Byte.SIZE + "/" + len); - } - - // Fill it - rov.setLength(recordOf.size()); - for (int position = 0; position < recordOf.size(); position++) { - rov.setField(position, recordOf.get(position)); - } // End of 'for' statement - - return rov; - } - - - @Override - public CodecBuffer encode(Value value) { -// TERFactory.getInstance().logDebug(">>> security.RecordOf.encode: " + value.getType().getName()); - - CodecBuffer buf = super.encode(value); - CodecBuffer bufLen = new CodecBuffer(TlsHelper.getInstance().size2tls(buf.getNbBytes())); - bufLen.append(buf); - return bufLen; - } - -} // End of class RecordOf diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/RegionDictionary.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/RegionDictionary.java deleted file mode 100644 index d2a407297f624732c2ea9082b829c5749ff0918b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/RegionDictionary.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Enumerated; - -public class RegionDictionary extends Enumerated { - - public RegionDictionary(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("RegionDictionaryLen", "8"); - } - -} // End of class RegionDictionary \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SecPayload.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SecPayload.java deleted file mode 100644 index b70242079d686e56fb0eb0d219dc3c492e34f773..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SecPayload.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SecPayload extends Record { - - final byte c_signed_external = 0x03; - - public SecPayload(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SecPayloadTypeLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SecPayload.postEncodeField: " + fieldName); - - if (fieldName.equals("data")) { - // Store first the octetstring length as specified in Draft ETSI TS 103 097 V1.1.14 Clause 4.2 - CodecBuffer bufLen = new CodecBuffer(new byte[] { (byte)buf.getNbBytes() } ); - bufLen.append(buf); - buf.overwriteWith(bufLen); - } - } - - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SecPayload.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - mainCodec.setPresenceHint("data", buf.getBytes(0, 1)[0] != c_signed_external); - } else if (fieldName.equals("data") && (mainCodec.getPresenceHint("data") == true)) { - int len = (int) TlsHelper.getInstance().tls2size(buf); -// TERFactory.getInstance().logDebug("SecPayload.preDecodeField: len = " + len); - mainCodec.setHint("octetstringLen", Integer.toString(len)); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SecPayload.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class SecPayload \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SecuredMessage.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SecuredMessage.java deleted file mode 100644 index 82103061abffbcfbb1bfc1391f4c651dbc416dc6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SecuredMessage.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; - -public class SecuredMessage extends Record { - - public SecuredMessage(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SecuredMessage.postEncodeField: " + fieldName); - - } - -} // End of class SecuredMessage \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ServiceSpecificPermissions.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ServiceSpecificPermissions.java deleted file mode 100644 index 2dba0799749fa3b24eb956c68549000d3d9b4e38..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ServiceSpecificPermissions.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class ServiceSpecificPermissions extends Record { - - public ServiceSpecificPermissions(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Oct1Len", "1"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> ServiceSpecificPermissions.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ServiceSpecificPermissions.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("sspContainer")) { - mainCodec.setPresenceHint(fieldName, true); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ServiceSpecificPermissions.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class ServiceSpecificPermissions diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Signature.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Signature.java deleted file mode 100644 index 3db11f07fd69059d8b48d49b4908b89e021d54bd..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Signature.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class Signature extends Record { - - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecdsa_nistp256_with_sha256 = 0x00; - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecies_nistp2561 = 0x01; - - public Signature(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("PublicKeyAlgorithmLen", "8"); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> Signature.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - if (fieldName.equals("algorithm")) { - if (buf.getBytes(0, 1)[0] == e_ecdsa_nistp256_with_sha256) { - mainCodec.setHint("SignatureContainer", "ecdsa_signature"); - } else if (buf.getBytes(0, 1)[0] == e_ecies_nistp2561) { - mainCodec.setHint("SignatureContainer", "signature_"); - } - } - } - -} // End of class Signature diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfo.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfo.java deleted file mode 100644 index 11faba49d400dc40abbdfc1c35fdd4ac8edbe87d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfo.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -/** - * @desc Information about the signer of a message - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.10 SignerInfo - */ -public class SignerInfo extends Record { - - final byte c_self = 0x00; /** The data is self-signed */ - final byte c_certificate_digest_with_sha256 = 0x01; /** An 8 octet digest of the relevant certificate */ - final byte c_certificate = 0x02; /** The relevant certificate itself */ - final byte c_certificate_chain = 0x03; /** A complete certificate chain */ - final byte c_certificate_digest_with_other_algorithm = 0x04; /** An 8 octet digest */ - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public SignerInfo(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("SignerInfoTypeLen", "8"); - mainCodec.setHint("HashedId8Len", "8"); - } - - /** - * @desc Set the variant according to the SignerInfo type - * @see See Draft ETSI TS 103 097 V1.1.14 Clause 4.2.11 SignerInfoType - */ - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SignerInfo.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type_ = buf.getBytes(0, 1)[0]; - mainCodec.setPresenceHint("signerInfo", (boolean)(type_ != c_self)); - switch (type_) { - case (byte)c_self: - // Nothing to do - break; - case (byte)c_certificate_digest_with_sha256: - mainCodec.setHint("SignerInfoContainer", "digest"); - break; - case (byte)c_certificate: - mainCodec.setHint("SignerInfoContainer", "certificate"); - break; - case (byte)c_certificate_chain: - mainCodec.setHint("SignerInfoContainer", "certificates"); - break; - case (byte)c_certificate_digest_with_other_algorithm: - mainCodec.setHint("SignerInfoContainer", "certificateWithAlgo"); - break; - default: - mainCodec.setHint("SignerInfoContainer", "info"); - break; - } // End of 'switch' statement - } - } - -} // End of class SignerInfo \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfoContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfoContainer.java deleted file mode 100644 index d4aeadf8db174c0a88d504e46c35cd6f15375a40..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SignerInfoContainer.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class SignerInfoContainer extends Union { - - public SignerInfoContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> SignerInfoContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("certificates")) { - // TODO To be continued - } else if (uv.getPresentVariantName().equals("info")) { - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class SignerInfoContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SspCAM.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SspCAM.java deleted file mode 100644 index e146f7f51059f46990c516d19376b4af38c73662..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SspCAM.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SspCAM extends Record { - - public SspCAM(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Bit1Len", "1"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SspCAM.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SspCAM.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SspCAM.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - } - -} // End of class SspCAM diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SspDENM.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SspDENM.java deleted file mode 100644 index 61aea6fa6bce71508f2dfe8800cec3e562703a7d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SspDENM.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SspDENM extends Record { - - public SspDENM(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Bit1Len", "1"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SspDENM.postEncodeField: " + fieldName); - - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SspDENM.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SspDENM.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - } - -} // End of class SspDENM diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAssurance.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAssurance.java deleted file mode 100644 index b694b401287fca1417c4f3d4849f134facf0479b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAssurance.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SubjectAssurance extends Record { - - public SubjectAssurance(MainCodec mainCodec) { - super(mainCodec); -// setLengths(); -// } -// -// private void setLengths() { -// mainCodec.setHint("Bit2Len", "2"); -// mainCodec.setHint("Bit3Len", "3"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SubjectAssurance.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectAssurance.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectAssurance.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class SubjectAssurance \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttribute.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttribute.java deleted file mode 100644 index 96ee2126e524a903789b1db868b1777626afe57e..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttribute.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SubjectAttribute extends Record { - - final byte c_verification_key = 0x00; - final byte c_encryption_key = 0x01; - final byte c_assurance_level = 0x02; - final byte c_reconstruction_value = 0x03; - final byte c_its_aid_list = 0x20; - final byte c_its_aid_ssp_list = 0x21; - - public SubjectAttribute(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SubjectAttributeTypeLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SubjectAttribute.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectAttribute.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type_ = buf.getBytes(0, 1)[0]; - switch (type_) { - case (byte)c_verification_key: - // No break; - case (byte)c_encryption_key: - mainCodec.setHint("SubjectAttributeContainer", "key"); // Set variant - break; - case (byte)c_reconstruction_value: - mainCodec.setHint("SubjectAttributeContainer", "rv"); // Set variant - break; - case (byte)c_assurance_level: - mainCodec.setHint("SubjectAttributeContainer", "assurance_level"); // Set variant - break; - case (byte)c_its_aid_list: - mainCodec.setHint("SubjectAttributeContainer", "its_aid_list"); // Set variant - break; - case (byte)c_its_aid_ssp_list: - mainCodec.setHint("SubjectAttributeContainer", "its_aid_ssp_list"); // Set variant - break; - default: - mainCodec.setHint("SubjectAttributeContainer", "other_attribute"); // Set variant - break; - } // End of 'switch' statement - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectAttribute.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class SubjectAttribute \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttributeContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttributeContainer.java deleted file mode 100644 index fbc4acc7aa3afdd9374a68dbd4e016bd950e10f1..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectAttributeContainer.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class SubjectAttributeContainer extends Union { - - public SubjectAttributeContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> SubjectAttributeContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("other_attribute")) { - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class SubjectAttributeContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectInfo.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectInfo.java deleted file mode 100644 index 7f406806c4137723ec3890a44ae34720efffc3eb..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/SubjectInfo.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class SubjectInfo extends Record { - - public SubjectInfo(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("SubjectTypeLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> SubjectInfo.postEncodeField: " + fieldName); - - if (fieldName.equals("subject_name")) { - CodecBuffer bufLen = new CodecBuffer(new byte[] { (byte)buf.getNbBytes() } ); - bufLen.append(buf); - buf.overwriteWith(bufLen); - } - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectInfo.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("subject_name")) { - int len = buf.readBits(Byte.SIZE)[0]; // FIXME It depends of the len value : <= 127 or > 127 - // FIXME Check for opaque length encoding - //int len = ByteHelper.byteArrayToInt(buf.readBits(Integer.SIZE)); // field_sizeLen is 1 bytes -// TERFactory.getInstance().logDebug("SubjectInfo.preDecodeField: len = " + len); - mainCodec.setHint("Oct0to31Len", Integer.toString(len)); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> SubjectInfo.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class SubjectInfo \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ThreeDLocation.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ThreeDLocation.java deleted file mode 100644 index f048953c03c99efda408705ecd15c93b29c5ecd1..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ThreeDLocation.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class ThreeDLocation extends Record { - - public ThreeDLocation(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("WGSLatitudeLen", "32"); - mainCodec.setHint("WGSLongitudeLen", "32"); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ThreeDLocation.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - if (fieldName.equals("elevation")) { - mainCodec.setHint("Oct2Len", "2"); - } - } - -} // End of class ThreeDLocation \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time32.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Time32.java deleted file mode 100644 index e0bc5f5a920c35cb399f26ecc79450ad99df387a..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time32.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Integer; - -public class Time32 extends Integer { - - public Time32(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Time32Len", "32"); - mainCodec.setHint("HeaderFieldContainer.expiry_timeLen", "32"); - mainCodec.setHint("ValidityRestrictionContainer.end_validityLen", "32"); - } - -} // End of class Time32 \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64.java deleted file mode 100644 index d04da83b5b1a122f135ed6b749ee813c1c1c6325..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Integer; - -public class Time64 extends Integer { - - public Time64(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("Time64Len", "64"); - mainCodec.setHint("HeaderFieldContainer.generation_timeLen", "64"); - } - -} // End of class Time64 \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64WithStandardDeviation.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64WithStandardDeviation.java deleted file mode 100644 index 0eb276eb4f87a32c186d1a90d0a59274d5855d6b..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/Time64WithStandardDeviation.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; - -public class Time64WithStandardDeviation extends Record { - - public Time64WithStandardDeviation(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("Time64Len", "64"); - } - -} // End of Time64WithStandardDeviation diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/TlsHelper.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/TlsHelper.java deleted file mode 100644 index 93e93adf88ed0b7d68a677e1ea3faca7a71e8778..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/TlsHelper.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.common.ByteHelper; - -public class TlsHelper { - - private static TlsHelper Instance = new TlsHelper(); - - public static TlsHelper getInstance() { return Instance; } - - private TlsHelper() { - } - - public byte[] size2tls(final int length) { - byte[] result = null; - if (length < 128) { // One byte length - result = new byte[] { (byte)length }; - } else { - long lv = length; - long bitLen = bitLength(lv); - long byteLen = byteLength(bitLen); - long flags = (long) ((byteLen | 1) << (byteLen * Byte.SIZE - bitLength(byteLen) - 1)); - long len = (long) (byteLen << (byteLen * Byte.SIZE - bitLength(byteLen) - 1)); - if ((flags & lv) != 0) { // We can encode the length on the MSB part - byteLen += 1; - len = (long) (byteLen << (byteLen * Byte.SIZE - bitLength(byteLen)) - 1); - } - result = ByteHelper.longToByteArray((long)(lv | len), (int) byteLen); - } - - return result; - } - - public long tls2size(CodecBuffer buf) { - // Sanity check - if (buf.getNbBytes() == 0) { - return 0; - } - - // Read the first byte - byte msb = buf.readBits(Byte.SIZE)[0]; - if ((msb & 0x80) == 0x00) { // Integer < 128 - return msb; - } else { - // Decode the length. The encoding of the length shall use at most 7 bits set to 1 (see Draft ETSI TS 103 097 V1.1.14 Clause 4.1 Presentation Language Table 1/8) - byte bit; - byte byteLen = 1; - do { - bit = (byte) ((byte) (msb << byteLen++) & 0x80); - } while (bit != 0x00); - // Set the IntX length - byte[] length = ByteHelper.concat(new byte[] { msb }, buf.readBytes(byteLen - 1)); - length[0] &= (byte)(Math.pow(2.0, 8 - byteLen + 1) - 1); - long lv = ByteHelper.byteArrayToLong(length); - return lv; - } - } - - public long bitLength(final long value) { - return (long) Math.ceil(Math.log(value) / Math.log(2)); - } - - public long byteLength(final long value) { - double d = value; // Convert int to double - return (long) Math.ceil(d / Byte.SIZE); - } - -} // End of class TlsHelper diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ToBeSignedCertificate.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ToBeSignedCertificate.java deleted file mode 100644 index e797b4d9565f93da2fd1a726da7a90559a3b42b0..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ToBeSignedCertificate.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class ToBeSignedCertificate extends Record { - - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecdsa_nistp256_with_sha256 = 0x00; - /** - * List of supported algorithms based on public key cryptography - */ - final byte e_ecies_nistp2561 = 0x01; - - public ToBeSignedCertificate(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> ToBeSignedCertificate.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ToBeSignedCertificate.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ToBeSignedCertificate.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class ToBeSignedCertificate diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerField.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerField.java deleted file mode 100644 index 2deed5267be0ff9c258ab14737f9f4d0f3f44b1d..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerField.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -/** - * @desc Information used by the security layer after processing the payload - * @see Draft ETSI TS 103 097 V1.1.14 Clause 5.6 TrailerField - */ -public class TrailerField extends Record { - - final byte c_signature = 0x01; - - /** - * Constructor - * @param mainCodec MainCodec reference - */ - public TrailerField(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - /** - * @desc Predefined field lengths - */ - private void setLengths() { - mainCodec.setHint("TrailerFieldTypeLen", "8"); - } - - /** - * @desc Set the variant according to the TrailerField type - * @see See Draft ETSI TS 103 097 V1.1.14 Clause 5.7 TrailerFieldType - */ - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> TrailerField.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type_ = buf.getBytes(0, 1)[0]; - switch (type_) { - case (byte)c_signature: - mainCodec.setHint("TrailerFieldContainer", "signature_"); - break; - default: - mainCodec.setHint("TrailerFieldContainer", "security_field"); - break; - } // End of 'switch' statement - } - } - -} // End of class TrailerField \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerFieldContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerFieldContainer.java deleted file mode 100644 index 9a634947f19ca6708e0f4f1027a6d6873a1a80e0..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/TrailerFieldContainer.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class TrailerFieldContainer extends Union { - - public TrailerFieldContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> TrailerFieldContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("security_field")) { - // FIXME Check for opaque length encoding depending of the length value : <= 127 or > 127 - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class TrailerFieldContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/TwoDLocation.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/TwoDLocation.java deleted file mode 100644 index 0daacbb394f83fa39197069b046df2a5dd72d6b3..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/TwoDLocation.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; - -public class TwoDLocation extends Record { - - public TwoDLocation(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("WGSLatitudeLen", "32"); - mainCodec.setHint("WGSLongitudeLen", "32"); - } - -} // End of class TwoDLocation \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestriction.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestriction.java deleted file mode 100644 index 87b96756232af253b0e26e7e3fd0a7863bdeac38..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestriction.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class ValidityRestriction extends Record { - - final byte c_time_end = 0x00; - final byte c_time_start_and_end = 0x01; - final byte c_time_start_and_duration = 0x02; - final byte c_region = 0x03; - - public ValidityRestriction(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("ValidityRestrictionTypeLen", "8"); - } - - @Override - protected void postEncodeField(String fieldName, CodecBuffer buf) { -// TERFactory.getInstance().logDebug(">>> ValidityRestriction.postEncodeField: " + fieldName); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ValidityRestriction.preDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - - if (fieldName.equals("type_")) { - byte type_ = buf.getBytes(0, 1)[0]; - switch (type_) { - case (byte)c_time_end: - mainCodec.setHint("ValidityRestrictionContainer", "end_validity"); // Set variant - break; - case (byte)c_time_start_and_end: - mainCodec.setHint("ValidityRestrictionContainer", "time_start_and_end"); // Set variant - break; - case (byte)c_time_start_and_duration: - mainCodec.setHint("ValidityRestrictionContainer", "time_start_and_duration"); // Set variant - break; - case (byte)c_region: - mainCodec.setHint("ValidityRestrictionContainer", "region"); // Set variant - break; - default: - mainCodec.setHint("SubjectAttributeContainer", "data"); // Set variant - break; - } // End of 'switch' statement - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { -// TERFactory.getInstance().logDebug(">>> ValidityRestriction.postDecodeField: " + fieldName + ", " + decodingHypothesis.getName() + ", " + rv.getType().getName()); - } - -} // End of class ValidityRestriction \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestrictionContainer.java b/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestrictionContainer.java deleted file mode 100644 index 7330c9df09de73065646f257495a74ae4972a053..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/security/ValidityRestrictionContainer.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.security; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.UnionValue; - -public class ValidityRestrictionContainer extends Union { - - public ValidityRestrictionContainer(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preEncode(CodecBuffer buf, UnionValue uv) { -// TERFactory.getInstance().logDebug(">>> ValidityRestrictionContainer.preEncode: " + uv.getType().getName() + ", " + uv.getPresentVariantName()); - - if (uv.getPresentVariantName().equals("data")) { - buf.appendBytes(new byte[] { (byte)((OctetstringValue)(uv.getVariant(uv.getPresentVariantName()))).getLength() } ); - } - } - -} // End of class ValidityRestrictionContainer diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/Plugin.java deleted file mode 100644 index 01ee4f492dad54d35be7ce98c2bab708b3d564bf..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/Plugin.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; -import org.etsi.ttcn.codec.generic.Record; - -public class Plugin { - - public static void init() { - // Basics - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "", UtRecord.class); - cf.setCodec(TciTypeClass.UNION, "UpperTester", "", UtUnion.class); - cf.setCodec(TciTypeClass.BOOLEAN, "UpperTester", "", UtBoolean.class); - // Gn - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtGnEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "Payload", UtPayload.class); - // Common - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtChangePosition", UtChangePosition.class); - // DENM - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "SituationContainer", Record.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmTrigger", UtDenmTrigger.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmUpdate", UtDenmUpdate.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmTermination", UtDenmTermination.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmTriggerResult", UtDenmTermination.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtDenmUpdateResult", UtDenmTermination.class); - // CAM - cf.setCodec(TciTypeClass.UNION, "UpperTester", "UtCamTrigger", UtCamTrigger.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtCamEventInd", UtEventInd.class); - // MAPEM/SPATEM - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtMapemEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSpatemEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtMapemSpatemTrigger", UtMapemSpatemTrigger.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtMapemSpatemTriggerResult", UtBoolean.class); - // IVIM - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimTrigger", UtIvimTrigger.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimUpdate", UtIvimUpdate.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimTermination", UtIvimTermination.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimTriggerResult", UtIvimTermination.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtIvimUpdateResult", UtIvimTermination.class); - // SREM/SSEM - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSremTrigger", UtSremTrigger.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSremTriggerResult", UtBoolean.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSremUpdate", UtSremUpdate.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSremUpdateResult", UtBoolean.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSremEventInd", UtEventInd.class); - cf.setCodec(TciTypeClass.RECORD, "UpperTester", "UtSsemEventInd", UtEventInd.class); - - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtBoolean.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtBoolean.java deleted file mode 100644 index 3caa53a4562f4d2b6b24b6f9f8a1003ac2c83bb9..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtBoolean.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Boolean; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtBoolean extends Boolean { - - public UtBoolean(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - Byte id = UtPduId.value(decodingHypothesis.getName()); - if(id != null) { - byte[] readId = buf.readBytes(1); - if(readId[0] != id) { - return null; - } - } - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - Byte id = UtPduId.value(value.getType().getName()); - if(id != null) { - return new CodecBuffer(new byte[] {id.byteValue()}); - } - return null; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtCamTrigger.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtCamTrigger.java deleted file mode 100644 index 62bfc6b10859df56bd59e5960efce431a4817a70..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtCamTrigger.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtCamTrigger extends UtUnion { - - public UtCamTrigger(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - return super.preEncode(value); - } - - private void setLengths() { - mainCodec.setHint("CurvatureValueLen", "16"); - mainCodec.setHint("SpeedValueLen", "16"); - mainCodec.setHint("AccelerationControlLen", "8"); - mainCodec.setHint("ExteriorLightsLen", "8"); - mainCodec.setHint("HeadingValueLen", "16"); - mainCodec.setHint("DriveDirectionLen", "8"); - mainCodec.setHint("YawRateValueLen", "16"); - mainCodec.setHint("VehicleRoleLen", "8"); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtChangePosition.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtChangePosition.java deleted file mode 100644 index 2f5f864515682937f2138cfcbf1165350f5857bd..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtChangePosition.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtChangePosition extends UtRecord { - - public UtChangePosition(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - return super.preEncode(value); - } - - private void setLengths() { - mainCodec.setHint("integerLen", "32"); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTermination.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTermination.java deleted file mode 100644 index d03662641fc4ba5d10dc4621626a2877d1703c24..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTermination.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.MainCodec; - -public class UtDenmTermination extends UtRecord { - - public UtDenmTermination(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("StationIDLen", "32"); - mainCodec.setHint("StationIDSign", "unsigned"); - mainCodec.setHint("SequenceNumberLen", "16"); - mainCodec.setHint("SequenceNumberSign", "unsigned"); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTrigger.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTrigger.java deleted file mode 100644 index f6d4540d25758c49b18425f533000fcc0affddb2..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmTrigger.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -import java.util.HashMap; -import java.util.Map; - -public class UtDenmTrigger extends UtRecord implements IMarkerCallback { - - private byte flags = 0x00; - - public UtDenmTrigger(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - CodecBuffer buf = super.preEncode(value); - CodecBuffer bufFlags = new CodecBuffer(); - bufFlags.setMarker("flags", 0, this); - buf.append(bufFlags); - return buf; - } - - private void setLengths() { - mainCodec.setHint("TimestampItsLen", "48"); - mainCodec.setHint("ValidityDurationLen", "24"); - mainCodec.setHint("InformationQualityLen", "8"); - mainCodec.setHint("CauseCodeTypeLen", "8"); - mainCodec.setHint("SubCauseCodeTypeLen", "8"); - mainCodec.setHint("RelevanceDistanceLen", "8"); - mainCodec.setHint("RelevanceTrafficDirectionLen", "8"); - mainCodec.setHint("TransmissionIntervalLen", "16"); - mainCodec.setHint("StationIDLen", "32"); - mainCodec.setHint("SequenceNumberLen", "16"); - mainCodec.setHint("integerLen", "8"); - mainCodec.setHint("AlacarteContainerLen", "8"); - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for(int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - CodecBuffer fieldBuf = mainCodec.encode(fieldValue); - postEncodeField(fields[i], fieldBuf); - buf.append(fieldBuf); - flags = (byte) (flags | (PresenceFlag.value(fields[i])).byteValue()); - } - else { - String hint = mainCodec.getHint(fieldValue.getType().getName() + "Len"); - if(hint != null) { - int lengthInBits = java.lang.Integer.parseInt(hint); - int lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - for(int j=0; j < lengthInBytes; j++) { - buf.appendBytes(new byte[]{0x00}); - } - } - } - } - - return buf; - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - CodecBuffer bufFlags = new CodecBuffer(new byte[] {flags}); - bufFlags.append(rightBuf); - rightBuf.setBytes(bufFlags.getBytes()); - } - - private enum PresenceFlag { - - /* DenmTrigger*/ - validityDuration(0x80), - repetitionDuration(0x40), - transmissionInterval(0x04), - repetitionInterval(0x02), - - /* Reserved */ - reserved(0x00); - - private byte value; - private static final Map PresenceFlags = new HashMap(); - - private PresenceFlag(int value) { - this.value = (byte)value; - } - - public static Byte value(String name) { - Byte res = PresenceFlags.get(name); - if(res == null) { - return value("reserved"); - } - return res; - } - - static { - for (PresenceFlag item : PresenceFlag.values()) { - PresenceFlags.put(item.name(), new Byte(item.value)); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmUpdate.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmUpdate.java deleted file mode 100644 index f78ee25d4edb1776920d4d4cc4ba7322b75ceb89..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtDenmUpdate.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: UtDenmUpdate.java,v 1.1.2.1 2015/03/30 11:19:16 dte Exp $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -import java.util.HashMap; -import java.util.Map; - -public class UtDenmUpdate extends UtRecord implements IMarkerCallback { - - private byte flags = 0x00; - - public UtDenmUpdate(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - CodecBuffer buf = super.preEncode(value); - CodecBuffer bufFlags = new CodecBuffer(); - bufFlags.setMarker("flags", 0, this); - buf.append(bufFlags); - return buf; - } - - private void setLengths() { - mainCodec.setHint("TimestampItsLen", "48"); - mainCodec.setHint("ValidityDurationLen", "24"); - mainCodec.setHint("InformationQualityLen", "8"); - mainCodec.setHint("CauseCodeTypeLen", "8"); - mainCodec.setHint("SubCauseCodeTypeLen", "8"); - mainCodec.setHint("RelevanceDistanceLen", "8"); - mainCodec.setHint("RelevanceTrafficDirectionLen", "8"); - mainCodec.setHint("TransmissionIntervalLen", "16"); - mainCodec.setHint("StationIDLen", "32"); - mainCodec.setHint("SequenceNumberLen", "16"); - mainCodec.setHint("integerLen", "8"); - mainCodec.setHint("AlacarteContainerLen", "8"); - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for(int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - CodecBuffer fieldBuf = mainCodec.encode(fieldValue); - postEncodeField(fields[i], fieldBuf); - buf.append(fieldBuf); - flags = (byte) (flags | (PresenceFlag.value(fields[i])).byteValue()); - } - else { - String hint = mainCodec.getHint(fieldValue.getType().getName() + "Len"); - if(hint != null) { - int lengthInBits = java.lang.Integer.parseInt(hint); - int lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - for(int j=0; j < lengthInBytes; j++) { - buf.appendBytes(new byte[]{0x00}); - } - } - } - } - - return buf; - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - CodecBuffer bufFlags = new CodecBuffer(new byte[] {flags}); - bufFlags.append(rightBuf); - rightBuf.setBytes(bufFlags.getBytes()); - } - - private enum PresenceFlag { - - /* DenmUpdate */ - //validityDuration(0x80), - situation(0x40), - relevanceDistance(0x20), - relevanceTrafficDirection(0x10), - trafficClass(0x08), - //transmissionInterval(0x04), - //repetitionInterval(0x02), - - /* Reserved */ - reserved(0x00); - - private byte value; - private static final Map PresenceFlags = new HashMap(); - - private PresenceFlag(int value) { - this.value = (byte)value; - } - - public static Byte value(String name) { - Byte res = PresenceFlags.get(name); - if(res == null) { - return value("reserved"); - } - return res; - } - - static { - for (PresenceFlag item : PresenceFlag.values()) { - PresenceFlags.put(item.name(), new Byte(item.value)); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtEventInd.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtEventInd.java deleted file mode 100644 index 03143bec4eabc8fa693f2f91dc881483b12daac4..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtEventInd.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; - -public class UtEventInd extends UtRecord { - - public UtEventInd(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - int length = ByteHelper.byteArrayToInt(buf.readBytes(Short.SIZE / Byte.SIZE)); - mainCodec.setHint(decodingHypothesis.getName() + "Len", Integer.toString(length)); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTermination.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTermination.java deleted file mode 100644 index 50d5489f7d021c15d9782a2fe951d0f4510730ab..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTermination.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.MainCodec; - -public class UtIvimTermination extends UtRecord { - - public UtIvimTermination(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("IviIdentificationNumberLen", "16"); - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTrigger.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTrigger.java deleted file mode 100644 index 1b00b34c83f1c93196d87790323ce80a13c6b1cc..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimTrigger.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtIvimTrigger extends UtRecord implements IMarkerCallback { - - private byte flags = 0x00; - - public UtIvimTrigger(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - CodecBuffer buf = super.preEncode(value); - CodecBuffer bufFlags = new CodecBuffer(); - bufFlags.setMarker("flags", 0, this); - buf.append(bufFlags); - return buf; - } - - private void setLengths() { - mainCodec.setHint("TimestampItsLen", "48"); - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for(int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - CodecBuffer fieldBuf = mainCodec.encode(fieldValue); - postEncodeField(fields[i], fieldBuf); - buf.append(fieldBuf); - flags = (byte) (flags | (PresenceFlag.value(fields[i])).byteValue()); - } - else { - String hint = mainCodec.getHint(fieldValue.getType().getName() + "Len"); - if(hint != null) { - int lengthInBits = java.lang.Integer.parseInt(hint); - int lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - for(int j=0; j < lengthInBytes; j++) { - buf.appendBytes(new byte[]{0x00}); - } - } - } - } - - return buf; - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - CodecBuffer bufFlags = new CodecBuffer(new byte[] {flags}); - bufFlags.append(rightBuf); - rightBuf.setBytes(bufFlags.getBytes()); - } - - private enum PresenceFlag { - - /* DenmTrigger*/ - validFrom(0x80), - validTo(0x40), - repetitionInterval(0x20), - - /* Reserved */ - reserved(0x00); - - private byte value; - private static final Map PresenceFlags = new HashMap(); - - private PresenceFlag(int value) { - this.value = (byte)value; - } - - public static Byte value(String name) { - Byte res = PresenceFlags.get(name); - if(res == null) { - return value("reserved"); - } - return res; - } - - static { - for (PresenceFlag item : PresenceFlag.values()) { - PresenceFlags.put(item.name(), new Byte(item.value)); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimUpdate.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimUpdate.java deleted file mode 100644 index 2c4d6d09241576748e3be1f8feb4a4fa52d434a0..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtIvimUpdate.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import java.util.HashMap; -import java.util.Map; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtIvimUpdate extends UtRecord implements IMarkerCallback { - - private byte flags = 0x00; - - public UtIvimUpdate(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - setLengths(); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - setLengths(); - CodecBuffer buf = super.preEncode(value); - CodecBuffer bufFlags = new CodecBuffer(); - bufFlags.setMarker("flags", 0, this); - buf.append(bufFlags); - return buf; - } - - private void setLengths() { - mainCodec.setHint("TimestampItsLen", "48"); - } - - @Override - public CodecBuffer encode(Value value) { - - RecordValue rv = (RecordValue)value; - String[] fields = rv.getFieldNames(); - CodecBuffer buf = new CodecBuffer(); - - for(int i=0; i < fields.length; i++) { - Value fieldValue = rv.getField(fields[i]); - if(!fieldValue.notPresent()) { - CodecBuffer fieldBuf = mainCodec.encode(fieldValue); - postEncodeField(fields[i], fieldBuf); - buf.append(fieldBuf); - flags = (byte) (flags | (PresenceFlag.value(fields[i])).byteValue()); - } - else { - String hint = mainCodec.getHint(fieldValue.getType().getName() + "Len"); - if(hint != null) { - int lengthInBits = java.lang.Integer.parseInt(hint); - int lengthInBytes = lengthInBits / 8 + (((lengthInBits % 8) > 0)?1:0); - for(int j=0; j < lengthInBytes; j++) { - buf.appendBytes(new byte[]{0x00}); - } - } - } - } - - return buf; - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - CodecBuffer bufFlags = new CodecBuffer(new byte[] {flags}); - bufFlags.append(rightBuf); - rightBuf.setBytes(bufFlags.getBytes()); - } - - private enum PresenceFlag { - - /* IvimUpdate */ - validFrom(0x80), - validTo(0x40), - repetitionInterval(0x20), - - /* Reserved */ - reserved(0x00); - - private byte value; - private static final Map PresenceFlags = new HashMap(); - - private PresenceFlag(int value) { - this.value = (byte)value; - } - - public static Byte value(String name) { - Byte res = PresenceFlags.get(name); - if(res == null) { - return value("reserved"); - } - return res; - } - - static { - for (PresenceFlag item : PresenceFlag.values()) { - PresenceFlags.put(item.name(), new Byte(item.value)); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtMapemSpatemTrigger.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtMapemSpatemTrigger.java deleted file mode 100644 index 03fba6afd8855c44b93922c79de55821687ca4a3..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtMapemSpatemTrigger.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.MainCodec; - -public class UtMapemSpatemTrigger extends UtRecord { - - public UtMapemSpatemTrigger(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("EventLen", "8"); - } - -} // End of class UtMapSpatTrigger diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPayload.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPayload.java deleted file mode 100644 index 66b0b69207ce50014b4433b4b6d30d8764ab00ab..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPayload.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL: $ - * $Id: $ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.Value; - -public class UtPayload extends Record implements IMarkerCallback { - - public UtPayload(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public CodecBuffer preEncode(Value value) { - - CodecBuffer buf = new CodecBuffer(new byte[] {(byte)0x00, (byte)0x00}); - buf.setMarker("payloadLength", 0, this); - - return buf; - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - - if(markerName.equals("payloadLength")) { - int length = (rightBuf.getNbBits() - 16) / 8; - CodecBuffer preserveRightBuf = rightBuf.getBuffer(16, rightBuf.getNbBits() - 16); - rightBuf.setBytes(ByteHelper.intToByteArray(length, 2)); - rightBuf.append(preserveRightBuf); - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPduId.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPduId.java deleted file mode 100644 index cb007ee5b4f9bc40dfba8b3c849abeced417b390..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtPduId.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import java.util.HashMap; -import java.util.Map; - -public enum UtPduId { - - /* From LibItsCommon_TypesAndValues */ - UtInitialize(0x00), - UtInitializeResult(0x01), - UtChangePosition(0x02), - UtChangePositionResult(0x03), - UtChangePseudonym(0x04), - UtChangePseudonymResult(0x05), - UtActivatePositionTime(0x06), - UtActivatePositionTimeResult(0x07), - UtDeactivatePositionTime(0x08), - UtDeactivatePositionTimeResult(0x09), - UtResult(0x24), // FIXME: obsolete - - /* From LibItsDenm_TypesAndValues */ - UtDenmTrigger(0x10), - UtDenmTriggerResult(0x11), - UtDenmUpdate(0x12), - UtDenmUpdateResult(0x13), - UtDenmTermination(0x14), - UtDenmTerminationResult(0x15), - //reserved(0x16), - UtDenmEventInd(0x17), - - /* From LibItsCam_TypesAndValues */ - //reserved(0x20), - UtCamTriggerResult(0x21), - //reserved(0x22), - UtCamEventInd(0x23), - UtCamTrigger_changeCurvature(0x30), - UtCamTrigger_changeSpeed(0x31), - UtCamTrigger_setAccelerationControlStatus(0x32), - UtCamTrigger_setExteriorLightsStatus(0x33), - UtCamTrigger_changeHeading(0x34), - UtCamTrigger_setDriveDirection(0x35), - UtCamTrigger_changeYawRate(0x36), - UtCamTrigger_setStationType(0x39), - UtCamTrigger_setVehicleRole(0x3a), - UtCamTrigger_setEmbarkationStatus(0x3b), - UtCamTrigger_setPtActivation(0x3c), - UtCamTrigger_setDangerousGoods(0x3d), - UtCamTrigger_setDangerousGoodsExt(0x3e), - UtCamTrigger_setLightBarSireneStatus(0x3f), - - /* From LibItsGeoNetworking_TypesAndValues */ - //reserved(0x40), - UtGnTriggerResult(0x41), - //reserved(0x42), - UtGnTrigger_geoUnicast(0x50), - UtGnTrigger_geoBroadcast(0x51), - UtGnTrigger_geoAnycast(0x52), - UtGnTrigger_shb(0x53), - UtGnTrigger_tsb(0x54), - UtGnEventInd(0x55), - - /* From LibItsBtp_TypesAndValues */ - //reserved(0x60), - UtBtpTriggerResult(0x61), - //reserved(0x62), - UtBtpEventInd(0x63), - UtBtpTrigger_btpA(0x70), - UtBtpTrigger_btpB(0x71), - - /* From LibItsIpv6OverGeoNetworking_TypesAndValues */ - UtGn6Trigger(0x80), - UtGn6TriggerResult(0x81), - //reserved(0x82), - UtGn6EventInd(0x83), - UtGn6GetInterfaceInfo(0x84), - UtGn6GetInterfaceInfoResult(0x85), - - /* */ - //reserved(0x90), - UtSecResult(0x91), - //reserved(0x92), - UtSec_setCertificate(0x93), - UtSec_setPrivateKey(0x94), - UtSec_setTrustPoint(0x95), - - /* IS */ - /* From LibItsMapemSpatem_TypesAndValues */ - UtMapemSpatemTrigger(0xA0), - UtMapemSpatemTriggerResult(0xA1), - UtMapemEventInd(0xA2), - UtSpatemEventInd(0xA3), - /* From LibItsIvim_TypesAndValues */ - UtIvimTrigger(0xA4), - UtIvimTriggerResult(0xA5), - UtIvimUpdate(0xA6), - UtIvimUpdateResult(0xA7), - UtIvimTermination(0xA8), - UtIvimTerminationResult(0xA9), - UtIvimEventInd(0xAA), - /* From LibItsSremSsem_TypesAndValues */ - UtSremTrigger(0xAB), - UtSremTriggerResult(0xAC), - UtSremUpdate(0xAD), - UtSremUpdateResult(0xAE), - UtSremEventInd(0xAF), - UtSsemEventInd(0xB0), // FIXME Not good, try to merge UtSremTriggerResult & UtSremUpdateResult - - /* Reserved */ - reserved(0xFF); - - private byte value; - private static final Map UtPduIds = new HashMap(); - private static final Map UtPduNames = new HashMap(); - - private UtPduId(int value) { - this.value = (byte)value; - } - - public static Byte value(String name) { - return UtPduIds.get(name); - } - - public static String name(Byte value) { - return UtPduNames.get(value); - } - - static { - for (UtPduId item : UtPduId.values()) { - UtPduIds.put(item.name(), new Byte(item.value)); - UtPduNames.put(new Byte(item.value), item.name()); - } - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtRecord.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtRecord.java deleted file mode 100644 index 63bbeaf13bde9b796bfcae7dfe4c0702b6dfe228..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtRecord.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; - -public class UtRecord extends Record { - - public UtRecord(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - Byte id = UtPduId.value(decodingHypothesis.getName()); - if(id != null) { - byte[] readId = buf.readBytes(1); - if(readId[0] != id) { - return null; - } - } - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - - // Set Length for GeoShape - mainCodec.setHint("GeoShapeLen", "8"); - - Byte id = UtPduId.value(value.getType().getName()); - if(id != null) { - return new CodecBuffer(new byte[] {id.byteValue()}); - } - return null; - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremTrigger.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremTrigger.java deleted file mode 100644 index cb1e2506cce91b2145cc21e1166498ea938b04a4..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremTrigger.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.MainCodec; - -public class UtSremTrigger extends UtRecord { - - public UtSremTrigger(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("BasicVehicleRoleLen", "8"); - mainCodec.setHint("RequestImportanceLevelLen", "8"); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremUpdate.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremUpdate.java deleted file mode 100644 index 27beef116820fdc16125142e72b8d76d486da07c..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtSremUpdate.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.etsi.ttcn.codec.its.uppertester; - -import org.etsi.ttcn.codec.MainCodec; - -public class UtSremUpdate extends UtRecord { - - public UtSremUpdate(MainCodec mainCodec) { - super(mainCodec); - setLengths(); - } - - private void setLengths() { - mainCodec.setHint("RequestIDLen", "8"); - mainCodec.setHint("BasicVehicleRoleLen", "8"); - mainCodec.setHint("RequestImportanceLevelLen", "8"); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtUnion.java b/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtUnion.java deleted file mode 100644 index 115ce459075531cd0fbfec9fa096ba8325d48300..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/uppertester/UtUnion.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.uppertester; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.tci.Value; - -public class UtUnion extends Union { - - public UtUnion(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public Value decode(CodecBuffer buf, Type decodingHypothesis) { - - String variant = ""; - Byte type = new Byte((byte)(0x00FF & buf.readBytes(1)[0])); - Pattern variantNamePattern = Pattern.compile(decodingHypothesis.getName() + "_(\\S+)"); - - Matcher matcher = variantNamePattern.matcher(UtPduId.name(type)); - if (matcher.find()) { - variant = matcher.group(1); - } - else { - return null; - } - - mainCodec.setHint(decodingHypothesis.getName(), variant); - return super.decode(buf, decodingHypothesis); - } - - @Override - public CodecBuffer preEncode(Value value) { - - UnionValue uv = (UnionValue)value; - - Byte id = UtPduId.value(value.getType().getName() + "_" + uv.getPresentVariantName()); - if(id != null) { - return new CodecBuffer(new byte[] {id.byteValue()}); - } - return null; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiHelper.java b/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiHelper.java deleted file mode 100644 index 4bfaebeba11f5c5d16c5bace8977ac4b456013ea..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiHelper.java +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$$ - * $Id$$ - */ -package org.etsi.ttcn.codec.its.v2g; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.sax.SAXSource; -import javax.xml.transform.stream.StreamResult; - -import org.etsi.adapter.TERFactory; -import org.etsi.common.ByteHelper; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -import com.siemens.ct.exi.CodingMode; -import com.siemens.ct.exi.EXIFactory; -import com.siemens.ct.exi.EncodingOptions; -import com.siemens.ct.exi.FidelityOptions; -import com.siemens.ct.exi.GrammarFactory; -import com.siemens.ct.exi.SchemaIdResolver; -import com.siemens.ct.exi.api.sax.EXIResult; -import com.siemens.ct.exi.api.sax.EXISource; -import com.siemens.ct.exi.exceptions.EXIException; -import com.siemens.ct.exi.grammars.Grammars; -import com.siemens.ct.exi.helpers.DefaultEXIFactory; - -public class ExiHelper { - - private static String schemaId = "v2g"; - private static boolean locked = false; - protected static String handshakeSchemaName = "ttcn_PowerUp\\xsd\\V2G_CI_AppProtocol.xsd"; - protected static String v2gSchemaName = "ttcn_PowerUp\\xsd\\V2G_CI_MsgBody.xsd"; - - public static void setSchemaId(String schemaName) { - while(locked) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - TERFactory.getInstance().logError("Changing Schema ID:" +schemaName); - schemaId = schemaName; - } - - public static void lockSchemaId() { - locked = true; - } - - private static void unlockSchemaId() { - locked = false; - } - - public static byte[] encode(byte[] xmlInput) { - InputStream xmlIn = new ByteArrayInputStream(xmlInput); - ByteArrayOutputStream exiOut = new ByteArrayOutputStream(); - - //ByteHelper.dump("encode EXI", xmlInput); - TERFactory.getInstance().logDebug("encode XML:" + new String(xmlInput)); - - EXIFactory exiFactory = createEXIFactory(); - try { - EXIResult exiResult = new EXIResult(exiFactory); - exiResult.setOutputStream(exiOut); - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); - xmlReader.setContentHandler(exiResult.getHandler()); - xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", - exiResult.getLexicalHandler()); - xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", - exiResult.getLexicalHandler()); - xmlReader.parse(new InputSource(xmlIn)); - } catch (Exception e) { - TERFactory.getInstance().logError("ERROR: Unable to EXI-encode message: " + e.getMessage()); - e.printStackTrace(); - return xmlInput; - } - - ByteHelper.dump("encode EXI", exiOut.toByteArray()); - - return exiOut.toByteArray(); - } - - public static byte[] decode(byte[] exiInput) { - InputStream exiIn = new ByteArrayInputStream(exiInput); - ByteArrayOutputStream xmlOut = new ByteArrayOutputStream(); - - ByteHelper.dump("decode EXI", exiInput); - - EXIFactory exiFactory = createEXIFactory(); - try { - EXISource exiSource = new EXISource(exiFactory); - XMLReader xmlReader = exiSource.getXMLReader(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - SAXSource saxSource = new SAXSource(new InputSource(exiIn)); - saxSource.setXMLReader(xmlReader); - transformer.transform(saxSource, new StreamResult(xmlOut)); - } catch (Exception e) { - TERFactory.getInstance().logError("ERROR: Unable to EXI-decode message: " + e.getMessage()); - e.printStackTrace(); - unlockSchemaId(); - return exiInput; - } - - //ByteHelper.dump("decode XML:", xmlOut.toByteArray()); - try { - TERFactory.getInstance().logDebug("decode XML:" + xmlOut.toString("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - unlockSchemaId(); - return xmlOut.toByteArray(); - } - - private static EXIFactory createEXIFactory() { - - EXIFactory exiFactory = DefaultEXIFactory.newInstance(); - - try { - // Encoding options - EncodingOptions encodingOptions = EncodingOptions.createDefault(); - exiFactory.setEncodingOptions(encodingOptions); - - // Fidelity options - FidelityOptions fidelityOptions = FidelityOptions.createDefault(); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_STRICT, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_PREFIX, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_DTD, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_LEXICAL_VALUE, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_COMMENT, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_PI, false); - fidelityOptions.setFidelity(FidelityOptions.FEATURE_SC, false); - exiFactory.setFidelityOptions(fidelityOptions); - } - catch(Exception e) { - TERFactory.getInstance().logError("ERROR: Unable to setup EXIFactory: " + e.getMessage()); - e.printStackTrace(); - } - - // Coding mode - exiFactory.setCodingMode(CodingMode.BIT_PACKED); - - // Value partition capacity - exiFactory.setValuePartitionCapacity(0); - - // SCHEMA OPTIONS - loadGrammar(exiFactory); - - return exiFactory; - } - - private static void loadGrammar(EXIFactory exiFactory) { - GrammarFactory grammarFactory = GrammarFactory.newInstance(); - Grammars grammars = null; - MySchemaIdResolver schemaIdResolver = new MySchemaIdResolver(grammarFactory); - exiFactory.setSchemaIdResolver(schemaIdResolver); - try { - grammars = schemaIdResolver.resolveSchemaId(schemaId); - if (grammars != null) - exiFactory.setGrammars(grammars); - } catch (EXIException e) { - e.printStackTrace(); - } - } - - - private static class MySchemaIdResolver implements SchemaIdResolver { - - private GrammarFactory grammarFactory; - - public MySchemaIdResolver(GrammarFactory grammarFactory) { - this.grammarFactory = grammarFactory; - } - - @Override - public Grammars resolveSchemaId(String schemaId) throws EXIException { - Grammars grammars = null; - String explicitSchemaName = null; - if(schemaId.equals("handshake")) { - explicitSchemaName = handshakeSchemaName; - } - if(schemaId.equals("v2g")) { - explicitSchemaName = v2gSchemaName; - } - File schemaFile = new File(explicitSchemaName); - grammars = grammarFactory.createGrammars(schemaFile.getAbsolutePath()); - return grammars; - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiUnion.java b/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiUnion.java deleted file mode 100644 index 4634d3c44b936ca6e1c873d85b50300cfd003e31..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/ExiUnion.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.v2g; - -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.IMarkerCallback; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.tci.Value; - -public class ExiUnion extends Union implements IMarkerCallback { - - private static final byte V2G_IND = 0x01; - private static final byte APP_PROTO_IND = 0x02; - private static final byte SDP_IND = 0x03; - - public ExiUnion(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - public void preDecode(CodecBuffer buf, Type decodingHypothesis) { - String variant = ""; - boolean exiProcessing = false; - byte reqIndId = buf.readBytes(1)[0]; - - switch(reqIndId) { - case V2G_IND: - variant = "v2gIn"; - exiProcessing = true; - break; - case APP_PROTO_IND: - variant = "appProtoIn"; - exiProcessing = true; - break; - case SDP_IND: - variant = "sdpIn"; - break; - } - mainCodec.setHint(decodingHypothesis.getName(), variant); - - if(exiProcessing) { - byte[] exi = buf.getBytes(); - byte[] xml = ExiHelper.decode(exi); - buf.setBytes(xml); - } - else { - super.preDecode(buf, decodingHypothesis); - } - } - - @Override - public CodecBuffer preEncode(Value value) { - UnionValue uv = (UnionValue)value; - CodecBuffer buf = new CodecBuffer(); - byte reqIndId = 0x00; - - String variantTypeName = uv.getVariant(uv.getPresentVariantName()).getType().getName(); - if(variantTypeName.equals("V2G_Message")) { - reqIndId = V2G_IND; - } - else if(variantTypeName.equals("SupportedAppProtocol_Message")) { - reqIndId = APP_PROTO_IND; - } - else if(variantTypeName.equals("SDP_Message")) { - reqIndId = SDP_IND; - } - buf.setBytes(new byte[] {reqIndId}); - - if(reqIndId == V2G_IND || reqIndId == APP_PROTO_IND) { - buf.setMarker("exiEncode", 0, this); - return buf; - } - else { - return super.preEncode(value); - } - } - - @Override - public void run(String markerName, CodecBuffer leftBuf, CodecBuffer rightBuf) { - - if(markerName.equals("exiEncode")) { - byte[] xml = rightBuf.getBytes(); - byte[] exi = ExiHelper.encode(xml); - rightBuf.setBytes(exi); - } - } - -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Plugin.java deleted file mode 100644 index 18ff0c5f13abd6081a3fb2950bda21237ec820b1..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Plugin.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.v2g; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - cf.setCodec(TciTypeClass.UNION, "LibItsV2G", "Sdp_Payload", Sdp_Payload.class); - cf.setCodec(TciTypeClass.UNION, "LibIts_Interface", "V2Gind", ExiUnion.class); - cf.setCodec(TciTypeClass.UNION, "LibIts_Interface", "V2Greq", ExiUnion.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Sdp_Payload.java b/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Sdp_Payload.java deleted file mode 100644 index 65ee39b16034314cc519421c9289ad4eb53c9ec5..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/its/v2g/Sdp_Payload.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @author ETSI / STF462 / Alexandre Berge - * @version $URL$ - * $Id$ - */ -package org.etsi.ttcn.codec.its.v2g; - -import org.etsi.adapter.TERFactory; -import org.etsi.ttcn.codec.CodecBuffer; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.tci.Type; - -public class Sdp_Payload extends Union { - - public Sdp_Payload(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - String variant = ""; - switch(buf.getNbBytes()) { - case 2: - variant = "sdpRequest"; - break; - case 20: - variant = "sdpResponse"; - break; - default: - TERFactory.getInstance().logError("Unable to decode " + decodingHypothesis.getName()); - return; - } - mainCodec.setHint(decodingHypothesis.getName(), variant); - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedIpv6ExtHeader.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedIpv6ExtHeader.java deleted file mode 100644 index d114c5c80dea275fa0c8a72faf0b2e536a5307b1..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedIpv6ExtHeader.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class CompressedIpv6ExtHeader extends Record { - - public CompressedIpv6ExtHeader(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("inlineNextHeader")) { - if(((EnumeratedValue)(rv.getField("nextHeader"))).getInt() != 0) { - mainCodec.setPresenceHint(fieldName, false); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedTrafficClass.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedTrafficClass.java deleted file mode 100644 index f91aa4eb1673c29b7a727954a6c24b2bcd049a69..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/CompressedTrafficClass.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class CompressedTrafficClass extends Record { - - public CompressedTrafficClass(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - int tc = Integer.parseInt(mainCodec.getHint("trafficClass")); - - switch(tc) { - case 1: - mainCodec.setPresenceHint("dscp", false); - mainCodec.setPresenceHint("reserved2", false); - break; - case 2: - mainCodec.setPresenceHint("flowLabel", false); - mainCodec.setPresenceHint("reserved1", false); - mainCodec.setPresenceHint("reserved2", false); - break; - } - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/IphcHeader.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/IphcHeader.java deleted file mode 100644 index ca7e6d452a3d6f6bd2f63532e973fe46ee788001..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/IphcHeader.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class IphcHeader extends Record { - - public IphcHeader(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("inlineSourceAddress")) { - int sac = ((EnumeratedValue)(rv.getField("sac"))).getInt(); - int sam = ((EnumeratedValue)(rv.getField("sam"))).getInt(); - int saLen = 0; - switch(sam) { - case 0: - if(sac == 0) { - saLen = 128; - } - else { - mainCodec.setPresenceHint(fieldName, false); - return; - } - break; - case 1: - saLen = 64; - break; - case 2: - saLen = 16; - break; - case 3: - mainCodec.setPresenceHint(fieldName, false); - return; - } - - mainCodec.setHint("CompressedIpv6AddressLen", Integer.toString(saLen / 8)); - } - - else if(fieldName.equals("inlineDestinationAddress")) { - int dac = ((EnumeratedValue)(rv.getField("dac"))).getInt(); - int dam = ((EnumeratedValue)(rv.getField("dam"))).getInt(); - int m = ((EnumeratedValue)(rv.getField("m"))).getInt(); - int daLen = 0; - - if(m == 0) { - switch(dam) { - case 0: - if(dac == 0) { - daLen = 128; - } - else { - mainCodec.setPresenceHint(fieldName, false); - return; - } - break; - case 1: - daLen = 64; - break; - case 2: - daLen = 16; - break; - case 3: - mainCodec.setPresenceHint(fieldName, false); - return; - } - } - else { - if(dac == 0) { - switch(dam) { - case 0: - daLen = 128; - break; - case 1: - daLen = 48; - break; - case 2: - daLen = 32; - break; - case 3: - daLen = 8; - break; - } - } - else { - if(dam == 0) { - daLen = 48; - } - else { - mainCodec.setPresenceHint(fieldName, false); - return; - } - } - } - mainCodec.setHint("CompressedIpv6AddressLen", Integer.toString(daLen / 8)); - } - } - - @Override - protected void postDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("trafficClass")) { - int tc = ((EnumeratedValue)(rv.getField(fieldName))).getInt(); - if(tc == 3) { - mainCodec.setPresenceHint("compressedTrafficClass", false); - } - mainCodec.setHint("trafficClass", Integer.toString(tc)); - } - - else if(fieldName.equals("nextHeader")) { - if(((EnumeratedValue)(rv.getField(fieldName))).getInt() != 0) { - mainCodec.setPresenceHint("inlineNextHeader", false); - mainCodec.setHint("NhcHeaderListMore", "true"); - } - else { - mainCodec.setHint("NhcHeaderListMore", "false"); - } - } - - else if(fieldName.equals("inlineNextHeader")) { -// int nh = ((IntegerValue)(rv.getField(fieldName))).getInteger(); TTWB iterface is getInt, TCI shall be getInteger - int nh = mainCodec.getTciCDRequired().getInteger((IntegerValue)(rv.getField(fieldName))); - mainCodec.setHint("Ipv6NextHeader", Integer.toString(nh)); - if(nh == 0 || nh == 60 || nh == 43 || nh == 44) { - mainCodec.setHint("ExtensionHeaderListMore", "true"); - } - else { - mainCodec.setHint("ExtensionHeaderListMore", "false"); - } - } - - else if(fieldName.equals("hopLimit")) { - if(((EnumeratedValue)(rv.getField(fieldName))).getInt() != 0) { - mainCodec.setPresenceHint("inlineHopLimit", false); - } - } - - else if(fieldName.equals("cid")) { - if(((EnumeratedValue)(rv.getField(fieldName))).getInt() == 0) { - mainCodec.setPresenceHint("cidExtension", false); - } - } - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanEncapsulatedHeader.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanEncapsulatedHeader.java deleted file mode 100644 index a1fddab271b810024893b925b3c870ae29f3746f..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanEncapsulatedHeader.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.codec.generic.Union; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class LowpanEncapsulatedHeader extends Union { - - public LowpanEncapsulatedHeader(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecode(CodecBuffer buf, Type decodingHypothesis) { - - byte[] dispatch = null; - - dispatch = buf.getBits(0, 3); - if(dispatch[0] == 0x03) { - mainCodec.setHint(decodingHypothesis.getName(), "ipch"); - return; - } - - dispatch = buf.getBits(0, 8); - if(dispatch[0] == 0x41 ) { - mainCodec.setHint(decodingHypothesis.getName(), "uncompressedIpv6"); - return; - } - - mainCodec.setHint(decodingHypothesis.getName(), "unknown"); - mainCodec.setHint("octetstringLen", Integer.toString(buf.getNbBytes())); - mainCodec.setHint(".unknownLen", Integer.toString(buf.getNbBytes())); - return; - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanFragmentationHeader.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanFragmentationHeader.java deleted file mode 100644 index fcfdc6df1fb7066e56e48ac07bfcfb9aa3afaf01..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/LowpanFragmentationHeader.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class LowpanFragmentationHeader extends Record { - - public LowpanFragmentationHeader(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - if(fieldName.equals("meshAddressingHdr")) { - if(mainCodec.getHint("fragmentationHdr").equals("Frag1")) { - mainCodec.setPresenceHint("offset", false); - } - } - } -} diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/Plugin.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/Plugin.java deleted file mode 100644 index 8cfdc83e003a7413efd20b84441dc12ae53508aa..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/Plugin.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.codec.CodecFactory; - -public class Plugin { - - public static void init() { - - CodecFactory cf = CodecFactory.getInstance(); - - cf.setCodec(TciTypeClass.RECORD, "6LoWPAN", "CompressedIpv6ExtHeader", CompressedIpv6ExtHeader.class); - cf.setCodec(TciTypeClass.RECORD, "6LoWPAN", "CompressedTrafficClass", CompressedTrafficClass.class); - cf.setCodec(TciTypeClass.RECORD, "6LoWPAN", "IphcHeader", IphcHeader.class); - cf.setCodec(TciTypeClass.RECORD, "6LoWPAN", "LowpanFragmentationHeader", LowpanFragmentationHeader.class); - cf.setCodec(TciTypeClass.UNION, "6LoWPAN", "LowpanEncapsulatedHeader", LowpanEncapsulatedHeader.class); - cf.setCodec(TciTypeClass.RECORD, "6LoWPAN", "SixLowpanFrame", SixLowpanFrame.class); - } -} \ No newline at end of file diff --git a/javasrc/codec/org/etsi/ttcn/codec/lowpan/SixLowpanFrame.java b/javasrc/codec/org/etsi/ttcn/codec/lowpan/SixLowpanFrame.java deleted file mode 100644 index 30304b47a5f2005c292acc6cf304c7ac60b48ae6..0000000000000000000000000000000000000000 --- a/javasrc/codec/org/etsi/ttcn/codec/lowpan/SixLowpanFrame.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.etsi.ttcn.codec.lowpan; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.codec.generic.Record; -import org.etsi.ttcn.codec.MainCodec; -import org.etsi.ttcn.codec.CodecBuffer; - -public class SixLowpanFrame extends Record { - - public SixLowpanFrame(MainCodec mainCodec) { - super(mainCodec); - } - - @Override - protected void preDecodeField(String fieldName, CodecBuffer buf, Type decodingHypothesis, RecordValue rv) { - - byte[] next = buf.getBytes(0, 1); - - if(fieldName.equals("meshAddressingHdr")) { - if((next[0] & 0xC0) != 0x80) { - mainCodec.setPresenceHint("meshAddressingHdr", false); - } - } - - else if(fieldName.equals("broadcastHdr")) { - if((next[0] & 0xFF) != 0x50) { - mainCodec.setPresenceHint("broadcastHdr", false); - } - } - - else if(fieldName.equals("fragmentationHdr")) { - if(((next[0] & 0xF8) != 0xC0) && ((next[0] & 0xF8) != 0xE0)) { - mainCodec.setPresenceHint("fragmentationHdr", false); - } - else { - if((next[0] & 0xF8) == 0xC0) { - mainCodec.setHint("fragmentationHdr", "Frag1"); - } - if((next[0] & 0xF8) == 0xE0) { - mainCodec.setHint("fragmentationHdr", "FragN"); - } - } - } - - else if(fieldName.equals("extHdrList")) { - String nhHint = mainCodec.getHint("Ipv6NextHeader"); - - if(nhHint != null) { - int nh = java.lang.Integer.parseInt(nhHint); - if(nh == 0 || nh == 60 || nh == 43 || nh == 44) { - mainCodec.setPresenceHint("extHdrList", true); - } - else { - mainCodec.setPresenceHint("extHdrList", false); - } - } - else { - mainCodec.setPresenceHint("extHdrList", false); - mainCodec.setPresenceHint("payload", false); - } - } - } -} diff --git a/javasrc/common/org/etsi/common/ByteHelper.java b/javasrc/common/org/etsi/common/ByteHelper.java deleted file mode 100644 index dac128aa887b86cd1d0667efaca59bea4b07684a..0000000000000000000000000000000000000000 --- a/javasrc/common/org/etsi/common/ByteHelper.java +++ /dev/null @@ -1,340 +0,0 @@ -/** - * @author ETSI / STF462 - * @version $URL$ - * $Id$ - */ -package org.etsi.common; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.etsi.adapter.TERFactory; - -public class ByteHelper { - - public static byte[] changeEndianness(byte [] in) { - byte[] out = new byte[in.length]; - for(int i=0; i < in.length; i++) { - out[in.length - i -1] = in[i]; - } - return out; - } - - public static byte[] intToByteArray(int value, int length, ByteOrder byteOrder) { - if(byteOrder == ByteOrder.LITTLE_ENDIAN) { - return changeEndianness(intToByteArray(value, length)); - } - return intToByteArray(value, length); - } - - public static byte[] intToByteArray(int value, int length) { - byte[] b = new byte[length]; - for (int i = length - 1; i >= 0; i--) { - int offset = (b.length - 1 - i) * 8; - b[i] = (byte) ((value >>> offset) & 0xFF); - } - return b; - } - - public static byte[] floatToByteArray(final float value) { - return ByteBuffer.allocate(Float.SIZE / Byte.SIZE).putFloat(value).array(); - } - - public static byte[] longToByteArray(long value, int length, ByteOrder byteOrder) { - if(byteOrder == ByteOrder.LITTLE_ENDIAN) { - return changeEndianness(longToByteArray(value, length)); - } - return longToByteArray(value, length); - } - - public static byte[] longToByteArray(long value, int length) { - byte[] b = new byte[length]; - for (int i = length - 1; i >= 0; i--) { - int offset = (b.length - 1 - i) * 8; - b[i] = (byte) ((value >>> offset) & 0xFF); - } - return b; - } - - /** Convert a byte array into a boolean - * - * @param b The byte array to convert - * @return The boolean value on success, false otherwise - */ - public static Boolean byteArrayToBoolean(byte[] b) { - // Sanity check - if ((b == null) || (b.length != 1)) { - return null; - } - - return new Boolean(b[0] == 0x01); - } // End of method byteArrayToBoolean - - public static Short byteArrayToShort(final byte[] b, ByteOrder byteOrder) { - if(byteOrder == ByteOrder.LITTLE_ENDIAN) { - return byteArrayToShort(changeEndianness(b)); - } - return byteArrayToShort(b); - } - - /** Convert a byte array into a short value assuming that the first byte is the most significant - * - * @param b The byte array to convert - * @return The short value on success, 'Integer.MAX_VALUE' otherwise - */ - public static Short byteArrayToShort(final byte[] b) { - // Sanity check - if ((b == null) || ((b.length * Byte.SIZE) > Short.SIZE)) { - return Short.MAX_VALUE; - } - - short value = 0; - for (Short i = 0; i < b.length; i++) { - value = (short)((value << 8) + (b[i] & 0xff)); - } - - return new Short(value); - } // End of method byteArrayToInt - - public static Integer byteArrayToInt(final byte[] b, ByteOrder byteOrder) { - if(byteOrder == ByteOrder.LITTLE_ENDIAN) { - return byteArrayToInt(changeEndianness(b)); - } - return byteArrayToInt(b); - } - - /** Convert a byte array into an integer assuming that the first byte is the most significant - * - * @param b The byte array to convert - * @return The integer value on success, 'Integer.MAX_VALUE' otherwise - */ - public static Integer byteArrayToInt(final byte[] b) { - // Sanity check - if ((b == null) || ((b.length * Byte.SIZE) > Integer.SIZE)) { - return Integer.MAX_VALUE; - } - - int value = 0; - for (int i = 0; i < b.length; i++) { - value = (value << 8) + (b[i] & 0xff); - } - - return new Integer(value); - } // End of method byteArrayToInt - - /** Convert a byte array into a signed integer assuming that padding bits are in first byte - * - * @param b The byte array to convert - * @param significantBits number of significant bits in the array - * @return The integer value - */ - public static int byteArrayToSignedInt(final byte[] b, final int significantBits) { - - int value = 0; - for (int i = 0; i < b.length; i++) { - value = (value << 8) + (b[i] & 0xff); - } - - int shift = 32 - significantBits; - - // Restore sign bit by shifting left and right - if(shift > 0) { - value <<= shift; - value >>= shift; - } - - return new Integer(value); - } - - public static Long byteArrayToLong(final byte[] b, ByteOrder byteOrder) { - if(byteOrder == ByteOrder.LITTLE_ENDIAN) { - return byteArrayToLong(changeEndianness(b)); - } - return byteArrayToLong(b); - } - - /** Convert a byte array into a Long assuming that the first byte is the most significant - * - * @param b The byte array to convert - * @return The Long value on success, 'Long.MAX_VALUE' otherwise - */ - public static Long byteArrayToLong(final byte[] b) { - // Sanity check - if ((b == null) || ((b.length * Byte.SIZE) > Long.SIZE)) { - return Long.MAX_VALUE; - } - - long value = 0; - for (int i = 0; i < b.length; i++) { - value = (value << 8) + (b[i] & 0xff); - } - - return new Long(value); - } // End of method byteArrayToLong - - public static Float byteArrayToFloat(final byte[] b) { - return ByteBuffer.wrap(b).getFloat(); - } - - public static byte[] hexStringToByteArray(final String s) { - String str = ""; - for(String ss : s.split("[^0-9A-Fa-f]")) { - str = str + ss; - } - int len = str.length(); - byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) - + Character.digit(str.charAt(i+1), 16)); - } - return data; - } - - public static byte[] concat(byte[]... arrays) { - int length = 0; - for (byte[] array : arrays) { - if(array != null) { - length += array.length; - } - } - byte[] result = new byte[length]; - int position = 0; - for (byte[] array : arrays) { - if(array != null) { - System.arraycopy(array, 0, result, position, array.length); - position += array.length; - } - } - return result; - } - - - /** Extract a sub part of a byte array - * @param array The original array - * @param offset The offset to start the extract operation - * @param length The number of bytes to extract - * @return The sub part of a provided byte array - */ - public static byte[] extract(final byte[] array, final int offset, final int length) { - // Sanity check - if ((array == null) || (array.length == 0) || (offset > array.length)) { - return null; - } - - byte[] result = new byte[length]; - System.arraycopy(array, offset, result, 0, length); - return result; - } - - /** - * This method convert a byte array containing the couple (length + string) into a string - * @param b The byte array to convert - * @return A string value - */ - public static String byteArrayWithLengthToString(final byte[] b) { - // Sanity check - if (b == null) { - return null; - } else if (b.length == 0) { - return ""; - } - - // Extract the length of the string - int length = byteArrayToInt(extract(b, 0, 4)); - // Extract the the string - String result = ""; - for (int i = 0; i < length; i++) { - result += (char)(b[4 + i]); - } // End of 'for' statement - - return result; - } - - public static String byteArrayToString(final byte[] buffer) { - - String result = ""; - if (buffer != null) { - for(int i=0; i < buffer.length; ++i) { - result += String.format("%02X", (byte)buffer[i]); - } - } - return result; - } - - public static byte[] fill(final byte[] buffer, final int length, final byte pattern) { - byte[] result = new byte[length]; - if (buffer == null) { // Fill it - for(int i = 0; i < length; ++i) { - result[i] = pattern; - } // End of 'for' statement - } else { // - for(int i = 0; i < length - buffer.length; ++i) { - result[length - i - 1] = pattern; - } // End of 'for' statement - System.arraycopy(buffer, 0, result, 0, buffer.length); - } - - return result; - } - - /** - * Dump a byte array in hex/ascii mode. - * @param label The dump label - * @param buffer The byte array to dump - */ - public synchronized static void dump(final String label, final byte[] buffer) - { - if ((buffer != null) && (buffer.length != 0)) - { - //TERFactory.getInstance().logDebug(label); - StringBuilder finalHexLine = new StringBuilder(); - StringBuilder finalCharLine = new StringBuilder(); - int nCounter = 0; - int nOffset = 0; - // Flush header. - //TERFactory.getInstance().logDebug(" HEX | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F : 0 1 2 3 4 5 6 7 8 9 A B C D E F "); - //TERFactory.getInstance().logDebug("-----|+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-:--+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+"); - for (int i = 0; i < buffer.length; ++i) - { - byte c = (byte)buffer[i]; - - String fmtHex = String.format("%02x ", c); - String fmtChar = String.format("%c ", Character.isISOControl((char)c) || c < 0 ? '.' : (char)c); - - if (nOffset % 16 == 0) - { - finalHexLine.append((String)String.format("%05x| ", nOffset)); - } - - finalHexLine.append(fmtHex); - finalCharLine.append(fmtChar); - if (nCounter == 15) - { - // Flush line. - //TERFactory.getInstance().logDebug(String.format("%s : %s", finalHexLine.toString(), finalCharLine.toString())); - // Reset buffer. - finalHexLine.delete(0, finalHexLine.length()); - finalCharLine.delete(0, finalCharLine.length()); - - nCounter = 0; - } - else - { - nCounter++; - } - nOffset++; - } - if (nCounter < 16) - { - // Pad till 15. - for (int i = nCounter; i < 16; i++) - { - finalHexLine.append(" "); - finalCharLine.append(" "); - } - // Flush line. - //TERFactory.getInstance().logDebug(String.format("%s : %s", finalHexLine.toString(), finalCharLine.toString())); - } - } - } -} diff --git a/javasrc/common/org/etsi/common/ITuple.java b/javasrc/common/org/etsi/common/ITuple.java deleted file mode 100644 index 0ceaf8e9c27e11d4abf8a27269e6cf1e34b226bb..0000000000000000000000000000000000000000 --- a/javasrc/common/org/etsi/common/ITuple.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.common; - -/** - * This interface provides mandatory method to be implemented by a Tuple {A, B} - * @param Type of the first member of the Tuple - * @param Type of the second member of the Tuple - */ -public interface ITuple { - - /** Retrieve the A element of the tuple - * @return the _a - */ - public abstract A getA(); - - /** Retrieve the B element of the tuple - * @return the _b - */ - public abstract B getB(); - -} \ No newline at end of file diff --git a/javasrc/common/org/etsi/common/KPM.java b/javasrc/common/org/etsi/common/KPM.java deleted file mode 100644 index abf88b67a58927cfca78d886ac0049a7301564eb..0000000000000000000000000000000000000000 --- a/javasrc/common/org/etsi/common/KPM.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Knuth-Morris-Pratt Algorithm implementation - * @author ETSI / STF481 - * @version $URL$ - * $Id$ - * Credit http://www.fmi.uni-sofia.bg/ - */ -package org.etsi.common; - -public class KPM { - - /** - * Search the data byte array for the first occurrence of the byte array pattern within given boundaries. - * @param data - * @param start First index in data - * @param stop Last index in data so that stop-start = length - * @param pattern What is being searched. '*' can be used as wildcard for "ANY character" - * @return - */ - public static int indexOf( byte[] data, int start, int stop, byte[] pattern) { - if( data == null || pattern == null) return -1; - - int[] failure = computeFailure(pattern); - - int j = 0; - - for( int i = start; i < stop; i++) { - while (j > 0 && ( pattern[j] != '*' && pattern[j] != data[i])) { - j = failure[j - 1]; - } - if (pattern[j] == '*' || pattern[j] == data[i]) { - j++; - } - if (j == pattern.length) { - return i - pattern.length + 1; - } - } - return -1; - } - - /** - * Computes the failure function using a boot-strapping process, - * where the pattern is matched against itself. - */ - private static int[] computeFailure(byte[] pattern) { - int[] failure = new int[pattern.length]; - - int j = 0; - for (int i = 1; i < pattern.length; i++) { - while (j>0 && pattern[j] != pattern[i]) { - j = failure[j - 1]; - } - if (pattern[j] == pattern[i]) { - j++; - } - failure[i] = j; - } - - return failure; - } -} // End of class KPM \ No newline at end of file diff --git a/javasrc/common/org/etsi/common/OperatorGUI.java b/javasrc/common/org/etsi/common/OperatorGUI.java deleted file mode 100644 index c30dc23d87d270fc8d4ce0902fc424bc52a95a0c..0000000000000000000000000000000000000000 --- a/javasrc/common/org/etsi/common/OperatorGUI.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @author ETSI - * @version $id$ - */ -package org.etsi.common; - -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.plaf.basic.BasicOptionPaneUI; - - -/** - * - */ -public class OperatorGUI extends JDialog implements ActionListener { - - /** - * - */ - private static final long serialVersionUID = 5803780216264271353L; - - private boolean result = false; - private JButton passButton = new JButton("Pass"); - private JButton failButton = new JButton("Fail"); - - /** - * Constructor - */ - public OperatorGUI() { - //empty - } - - public boolean pop(String msg) { - - // Get the size of the screen - Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); - - // Dialog settings - setTitle("Operator Action on SUT"); - setMinimumSize(new Dimension(300, 80)); - setAlwaysOnTop(true); - setModal(true); - setResizable(false); - int x = (dim.width - getWidth()) / 2; - int y = (dim.height - getHeight()) / 2; - setLocation(x, y); - - // Content - setLayout(new GridLayout(2, 1)); - add(new JLabel(msg)); - JPanel panel = new JPanel(); - panel.setLayout(new BasicOptionPaneUI.ButtonAreaLayout(isModal(), 2)); - panel.add(passButton); - panel.add(failButton); - add(panel); - passButton.addActionListener(this); - failButton.addActionListener(this); - - // Show ! - pack(); - setVisible(true); - return result; - } - - @Override - public void actionPerformed(ActionEvent arg0) { - if (arg0.getSource().equals(passButton)) { - result = true; - } - setVisible(false); - } - -} diff --git a/javasrc/common/org/etsi/common/Tuple.java b/javasrc/common/org/etsi/common/Tuple.java deleted file mode 100644 index 4e710277ea27f07f70c496810b0cdf81d114112a..0000000000000000000000000000000000000000 --- a/javasrc/common/org/etsi/common/Tuple.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.common; - -/** - * This class implements the ITuple interface - * @param Type of the first member of the Tuple - * @param Type of the second member of the Tuple - */ -public class Tuple implements ITuple { - - /** - * A element of the tuple - */ - private A _a; - - /** - * B element of the tuple - */ - private B _b; - - /** - * Constructor - * @param a The A element of the new tuple - * @param b The B element of the new tuple - */ - public Tuple(A a, B b) { - _a = a; - _b = b; - } - - /** - * Retrieve the A element of the tuple - * @return the _a - */ - @Override - public A getA() { - return _a; - } - - /** - * Retrieve the B element of the tuple - * @return the _b - */ - @Override - public B getB() { - return _b; - } -} diff --git a/javasrc/extfunc/org/etsi/its/extfunc/IItsExternalFunctionsProvider.java b/javasrc/extfunc/org/etsi/its/extfunc/IItsExternalFunctionsProvider.java deleted file mode 100644 index 89630f66de20adf41d9b4d2c57d29f09e1b10876..0000000000000000000000000000000000000000 --- a/javasrc/extfunc/org/etsi/its/extfunc/IItsExternalFunctionsProvider.java +++ /dev/null @@ -1,308 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $id$ - */ -package org.etsi.its.extfunc; - -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.RecordValue; - -/** - * This interface provides the list of the TTCN-3 external function to be implemented - * - * Refer to TTCN-3 modules LibItsGeoNetworking_Functions and LibItsCommon_Functions - */ -public interface IItsExternalFunctionsProvider { - - /** - * This external function gets the current time - * @return The current time in Epoch format - * - * TTCN-3 signature: - * external function fx_getCurrentTime() return TimestampIts; - */ - public IntegerValue fx_getCurrentTime(); - - /** - * This external function gets the tenths of a second in the current or next hour in units of 1/10th second from UTC time - * @return The current time in tenths of a second in the current or next hour in units of 1/10th second from UTC time - * - * TTCN-3 signature: - * external function fx_getCurrentTimeMark() return TimeMark; - */ - public IntegerValue fx_getCurrentTimeMark(); - - /** - * This external function gets the minutes of current UTC year - * @return The minutes of current UTC year - * - * TTCN-3 signature: - * external function fx_getMinuteOfTheYear() return MinuteOfTheYear; - */ - public IntegerValue fx_getMinuteOfTheYear(); - - /** - * This external function gets the milliseconds point in the current UTC minute - * @return The milliseconds point in the current UTC minute (0..60000) - * - * TTCN-3 signature: - * external function fx_getDSecond() return DSecond; - */ - public IntegerValue fx_getDSecond(); - - /** - * This external function gets the current time - * @param p_latitudeA Latitude of node A - * @param p_longitudeA Longitude of node A - * @param p_latitudeB Latitude of node B - * @param p_longitudeB Longitude of node B - * @return The current time in Epoch format - * - * TTCN-3 signature: - * external function fx_computeDistance(in UInt32 p_latitudeA, in UInt32 p_longitudeA, in UInt32 p_latitudeB, in UInt32 p_longitudeB) return float; - */ - public FloatValue fx_computeDistance(final IntegerValue p_latitudeA, final IntegerValue p_longitudeA, final IntegerValue p_latitudeB, final IntegerValue p_longitudeB); - - /** - * External function to compute a position using a reference position, a distance and an orientation - * @param p_iutLongPosVector Reference position - * @param p_distance Distance to the reference position (in meter) - * @param p_orientation Direction of the computed position (0 to 359; 0 means North) - * @param p_latitude Computed position's latitude - * @param p_longitude Computed position's longitude - * - * TTCN-3 signature: - * external function fx_computePositionUsingDistance(in UInt32 p_refLatitude, in Uint32 p_refLongitude, in integer p_distance, in integer p_orientation, out UInt32 p_latitude, out UInt32 p_longitude); - */ - public void fx_computePositionUsingDistance(final IntegerValue p_refLatitude, final IntegerValue p_refLongitude, final FloatValue p_distance, final IntegerValue p_orientation, IntegerValue p_latitude, IntegerValue p_longitude); - - /** - * External function to compute a position using a reference position, a distance and an orientation - * @param p_iutLongPosVector Reference position - * @param p_rotation Rotation value (in degrees) - * @param p_latitude Computed position's latitude - * @param p_longitude Computed position's longitude - * - * TTCN-3 signature: - * external function fx_computePositionFromRotation(in UInt32 p_refLatitude, in Uint32 p_refLongitude, in Uint32 p_cenLatitude, in Uint32 p_cenLongitude, in Int32 p_rotation, out UInt32 p_latitude, out UInt32 p_longitude); - */ - public void fx_computePositionFromRotation(final IntegerValue p_refLatitude, final IntegerValue p_refLongitude, final IntegerValue p_cenLatitude, final IntegerValue p_cenLongitude, final IntegerValue p_rotation, IntegerValue p_latitude, IntegerValue p_longitude); - - /** - * External function to compute radius of a given circular area - * @param p_squareMeters Square meters of an circular area - * @return Computed radius in meters - */ - public FloatValue fx_computeRadiusFromCircularArea(final FloatValue p_squareMeters); - - /** - * External function to compute timestamp based on current time - * @return Unix-Epoch-Time mod 2^32 - * - * TTCN-3 signature: - * external function fx_computeGnTimestamp() return UInt32; - */ - public IntegerValue fx_computeGnTimestamp(); - - /** - * @desc Calculate ICMPv6 checksum on pseudo header according RFC 4443 - Clause 2.3 - * @param p_sourceAddress Source address, - * @param p_destinationAddress Destination address - * @param p_payloadLength Upper-Layer Packet Length - * @param p_payload Upper-Layer payload - * @param p_nextHdr Next header value (e.g. 0x3a for ICMPv6) - * @return The checksum value - * @see RFC 2460 IPv6 Specification - * - * TTCN-3 signature: - * external function fx_computeIPv6CheckSum( - * in template (value) Ipv6Address p_sourceAddress, - * in template (value) Ipv6Address p_destinationAddress, - * in template (value) integer p_payloadLength, - * in template (value) octetstring p_payload, - * in template (value) integer p_nextHdr - * ) return Oct2; - *
-      * Pseudo header is defined by RFC 2460 - Clause 8.1
-      *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-      *  |                                                               |
-      *  +                                                               +
-      *  |                                                               |
-      *  +                         Source Address                        +
-      *  |                                                               |
-      *  +                                                               +
-      *  |                                                               |
-      *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-      *  |                                                               |
-      *  +                                                               +
-      *  |                                                               |
-      *  +                      Destination Address                      +
-      *  |                                                               |
-      *  +                                                               +
-      *  |                                                               |
-      *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-      *  |                   Upper-Layer Packet Length                   |
-      *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-      *  |                      zero                     |  Next Header  |
-      *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-      * 
- */ - public OctetstringValue fx_computeIPv6CheckSum( - final OctetstringValue p_sourceAddress, - final OctetstringValue p_destinationAddress, - final IntegerValue p_payloadLength, - final OctetstringValue p_payload, - final IntegerValue p_nextHdr - ); - - public OctetstringValue xf_parseIpv6Address(final CharstringValue p_textIpv6Address); - - /** - * @desc Produces a 256-bit (32-byte) hash value - * @param p_toBeHashedData Data to be used to calculate the hash value - * @return The hash value - */ - public OctetstringValue fx_hashWithSha256(final OctetstringValue p_toBeHashedData); - - /** - * @desc Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signaturee - * @param p_toBeSignedData The data to be signed - * @param p_privateKey The private key - * @return The signature value - */ - public OctetstringValue fx_signWithEcdsaNistp256WithSha256(final OctetstringValue p_toBeSignedData, final OctetstringValue/*IntegerValue*/ p_privateKey); - - /** - * @desc Verify the signature of the specified data - * @param p_toBeVerifiedData The data to be verified - * @param p_signature The signature - * @param p_ecdsaNistp256PublicKeyX The public key (x coordinate) - * @param p_ecdsaNistp256PublicKeyY The public key (y coordinate) - * @return true on success, false otherwise - */ - public BooleanValue fx_verifyWithEcdsaNistp256WithSha256(final OctetstringValue p_toBeVerifiedData, final OctetstringValue p_signature, final OctetstringValue p_ecdsaNistp256PublicKeyX, final OctetstringValue p_ecdsaNistp256PublicKeyY); - - /** - * @desc Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm - * @param p_privateKey The new private key value - * @param p_publicKeyX The new public key value (x coordinate) - * @param p_publicKeyX The new public key value (y coordinate) - * @return true on success, false otherwise - */ - public BooleanValue fx_generateKeyPair(OctetstringValue/*IntegerValue*/ p_privateKey, OctetstringValue p_publicKeyX, OctetstringValue p_publicKeyY); - - /** - * @desc Check that given polygon doesn't have neither self-intersections nor holes. - * @param p_region Polygonal Region - * @return true on success, false otherwise - */ - public BooleanValue fx_isValidPolygonalRegion(final RecordOfValue p_region); - - /** - * @desc Check if a polygonal regin is inside another one - * @param p_parent The main polygonal region - * @param p_region The polygonal region to be included - * @return true on success, false otherwise - * @verdict Unchanged - */ - public BooleanValue fx_isPolygonalRegionInside(final RecordOfValue p_parent, final RecordOfValue p_region); - - /** - * @desc Check that the location is inside a circular region - * @param p_region The circular region to consider - * @param p_location The device location - * @return true on success, false otherwise - * @verdict Unchanged - */ - public BooleanValue fx_isLocationInsideCircularRegion(final RecordValue p_region, final RecordValue p_location); - - /** - * @desc Check that the location is inside a rectangular region - * @param p_region The rectangular region to consider - * @param p_location The device location - * @return true on success, false otherwise - * @verdict Unchanged - */ - public BooleanValue fx_isLocationInsideRectangularRegion(final RecordOfValue p_region, final RecordValue p_location); - - /** - * @desc Check that the location is inside a polygonal region - * @param p_region The polygonal region to consider - * @param p_location The device location - * @return true on success, false otherwise - * @verdict Unchanged - */ - public BooleanValue fx_isLocationInsidePolygonalRegion(final RecordOfValue p_region, final RecordValue p_location); - - /** - * @desc Check if the location is inside an identified region - * @param p_region The identified region to consider - * @param p_location The device location - * @return true on success, false otherwise - * @verdict Unchanged - */ - public BooleanValue fx_isLocationInsideIdentifiedRegion(final RecordValue p_region, final RecordValue p_location); - - /** - * @desc Convert a spacial coordinate from DMS to Dms - * @param p_degrees The degrees (D) - * @param p_minutes The minutes (M) - * @param p_seconds The seconds (S) - * @param p_latlon The latitude/longitude: (N|S|E|W) - * @return The decimal coordinate on success, 0.0, otherwise - * @verdict Unchanged - */ - public FloatValue fx_dms2dd(final IntegerValue p_degrees, final IntegerValue p_minutes, final FloatValue p_seconds, final OctetstringValue p_latlon); - - /** - * @desc Load in memory cache the certificates available in the specified directory - * @param p_rootDirectory Root directory to access to the certificates identified by the certificate ID - * @param p_configId A configuration identifier - * @return true on success, false otherwise - */ - public BooleanValue fx_loadCertificates(final CharstringValue p_rootDirectory, final CharstringValue p_configId); - - /** - * @desc Unload from memory cache the certificates - * @return true on success, false otherwise - */ - public BooleanValue fx_unloadCertificates(); - - /** - * @desc Read the specified certificate - * @param p_certificateId the certificate identifier - * @param p_certificate the expected certificate - * @return true on success, false otherwise - */ - public BooleanValue fx_readCertificate(final CharstringValue p_certificateId, OctetstringValue p_certificate); - - /** - * @desc Read the specified certificate digest - * @param p_certificateId the certificate identifier - * @param p_certificate the expected certificate - * @return true on success, false otherwise - */ - public BooleanValue fx_readCertificateDigest(final CharstringValue p_certificateId, OctetstringValue p_certificate); - - /** - * @desc Read the signing private key for the specified certificate - * @param p_keysId the keys identifier - * @param p_key the signing private key - * @return true on success, false otherwise - */ - public BooleanValue fx_readSigningKey(final CharstringValue p_keysId, OctetstringValue p_key); - - /** - * @desc Read the encrypting private key for the specified certificate - * @param p_keysId the keys identifier - * @param p_key the encrypt private key - * @return true on success, false otherwise - */ - public BooleanValue fx_readEncryptingKey(final CharstringValue p_keysId, OctetstringValue p_key); - -} // End of interface IItsExternalFunctionsProvider diff --git a/javasrc/extfunc/org/etsi/its/extfunc/ItsExternalFunctionsProvider.java b/javasrc/extfunc/org/etsi/its/extfunc/ItsExternalFunctionsProvider.java deleted file mode 100644 index dd814ee45830df19f52cfe0880bafebe35a7228c..0000000000000000000000000000000000000000 --- a/javasrc/extfunc/org/etsi/its/extfunc/ItsExternalFunctionsProvider.java +++ /dev/null @@ -1,1003 +0,0 @@ -/** - * @authorSTF 424_ITS_Test_Platform - * @version $URL$ - * $Id$ - */ -package org.etsi.its.extfunc; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.ArrayList; -import java.util.logging.Logger; - -import org.etsi.adapter.GnssSupportFactory; -import org.etsi.adapter.IGnssSupport; -import org.etsi.adapter.TERFactory; -import org.etsi.certificates.CertificatesIOFactory; -import org.etsi.certificates.io.ICertificatesIO; -import org.etsi.codec.ITciCDWrapper; -import org.etsi.codec.TciCDWrapperFactory; -import org.etsi.common.ByteHelper; -import org.etsi.geodesic.DMS; -import org.etsi.geodesic.Positioning; -import org.etsi.geodesic.WGS84; -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.RecordValue; - -import de.fraunhofer.sit.c2x.CryptoLib; -import de.fraunhofer.sit.c2x.EcdsaP256KeyPair; - -/** - * This class implements external ITS function - * - * See TTCN-3 modules LibItsGeoNetworking_Functions and LibItsCommon_Functions - * - */ -public class ItsExternalFunctionsProvider implements IItsExternalFunctionsProvider { - - /** - * Module version - */ - public static final String Version = "1.0.0.0"; - - /** - * Unique instance of TciCDWrapper class - */ - private ITciCDWrapper _tcicdWrapper; - - /** - * Constant factor used for distance computation - */ - private static final double earthRadius = 6378137; - private static final double rbis = earthRadius * Math.PI / 180; - - private static final long ITS_REF_TIME = 1072915200000L; - - private static final String GNSS_SCENARIO_SUPPORT = "GnssScenarioSupport"; - private IGnssSupport GNSS; - private boolean gnssScenarioSupport; - - /** - * Reference to the ePassport files manager - */ - private ICertificatesIO _certCache = CertificatesIOFactory.getInstance(); - - /** - * Default ctor - */ - public ItsExternalFunctionsProvider() { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "Constructor", String.format("version:%s", Version)); - - _tcicdWrapper = TciCDWrapperFactory.getTciCDInstance(); - - try { - gnssScenarioSupport = ((BooleanValue) TERFactory.getInstance().getTaParameter(GNSS_SCENARIO_SUPPORT)).getBoolean(); - } - catch (Throwable th) { - gnssScenarioSupport = false; - } - if (gnssScenarioSupport) { - GNSS = GnssSupportFactory.getInstance(); - } - } - - /** - * This external function gets the current time - * - * @return The current time in ITS format - * - * TTCN-3 signature: external function fx_getCurrentTime() return - * TimestampIts; - */ - @Override - public synchronized IntegerValue fx_getCurrentTime() { - IntegerValue now = null; - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getCurrentTime"); - - if (gnssScenarioSupport) { - now = _tcicdWrapper.setInteger(GNSS.getGpsTime()); - } - else { -// TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider.fx_getCurrentTime: " + ((java.util.Date)formatter.parse(datestr)).getTime()); - now = _tcicdWrapper.setInteger( - new BigInteger( - 1, - ByteHelper.longToByteArray(System.currentTimeMillis() - ITS_REF_TIME, Long.SIZE / Byte.SIZE) - ) - ); - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getCurrentTime", String.format("%10d", _tcicdWrapper.getBigInteger(now))); - } - return now; - } // End of method fx_getCurrentTime - - @Override - public IntegerValue fx_getCurrentTimeMark() { - IntegerValue now = null; - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getCurrentTimeMark"); - - ZonedDateTime t = ZonedDateTime.now(ZoneOffset.UTC); - now = _tcicdWrapper.setInteger(new Integer((t.getMinute() * 60 + t.getSecond()) * 10)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getCurrentTimeMark", String.format("%4d", _tcicdWrapper.getBigInteger(now))); - return now; - } - - @Override - public IntegerValue fx_getMinuteOfTheYear() { - IntegerValue now = null; - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getMinuteOfTheYear"); - - ZonedDateTime t = ZonedDateTime.now(ZoneOffset.UTC); - now = _tcicdWrapper.setInteger(new Integer((t.getDayOfYear() - 1) * 24 * 60 + t.getHour() * 60 + t.getMinute())); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getMinuteOfTheYear", String.format("%4d", _tcicdWrapper.getBigInteger(now))); - return now; - } - - public IntegerValue fx_getDSecond() { - IntegerValue now = null; - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getDSecond"); - - ZonedDateTime t = ZonedDateTime.now(ZoneOffset.UTC); - int i = new Integer(t.getSecond() + Math.round(t.getNano() / 1000)); - if (i > 65535) { - i = 65535; - } - now = _tcicdWrapper.setInteger(i); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_getDSecond", String.format("%4d", _tcicdWrapper.getBigInteger(now))); - return now; - } - - /** - * This external function gets the current time - * - * @param p_latitudeA - * Latitude of node A - * @param p_longitudeA - * Longitude of node A - * @param p_latitudeB - * Latitude of node B - * @param p_longitudeB - * Longitude of node B - * @return The current time in Epoch format - * - * TTCN-3 signature: external function fx_computeDistance(in UInt32 - * p_latitudeA, in UInt32 p_longitudeA, in UInt32 p_latitudeB, in - * UInt32 p_longitudeB) return float; - */ - @Override - public synchronized FloatValue fx_computeDistance( - final IntegerValue p_latitudeA, final IntegerValue p_longitudeA, - final IntegerValue p_latitudeB, final IntegerValue p_longitudeB) { -// //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_computeDistance", -// String.format("%d, %d, %d, %d", -// p_latitudeA.getInteger(), -// p_longitudeA.getInteger(), -// p_latitudeB.getInteger(), -// p_longitudeB.getInteger())); - - // Initialise the returned value - FloatValue dist = _tcicdWrapper.getFloat(); - - double dlat = ( - new Double(_tcicdWrapper.getInteger(p_latitudeB)) - - new Double(_tcicdWrapper.getInteger(p_latitudeA)) - ) / 10000000; - double dlong = ( - new Double(_tcicdWrapper.getInteger(p_longitudeB)) - - new Double(_tcicdWrapper.getInteger(p_longitudeA)) - ) / 10000000; - - long d = Math.round(Math.sqrt(Math.pow(dlat * rbis, 2) + Math.pow(dlong * rbis * Math.cos(dlat), 2))); - - dist.setFloat(d); - - return dist; - } // End of method fx_computeDistance - - /** - * External function to compute a position using a reference position, a - * distance and an orientation - * - * @param p_iutLongPosVector - * Reference position - * @param p_distance - * Distance to the reference position (in meter) - * @param p_orientation - * Direction of the computed position (0 to 359; 0 means North) - * @param p_latitude - * Computed position's latitude - * @param p_longitude - * Computed position's longitude - * - * TTCN-3 signature: external function - * fx_computePositionUsingDistance(in LongPosVector - * p_iutLongPosVector, in integer p_distance, in integer - * p_orientation, out UInt32 p_latitude, out UInt32 p_longitude); - */ - @Override - public synchronized void fx_computePositionUsingDistance( - final IntegerValue p_refLatitude, - final IntegerValue p_refLongitude, final FloatValue p_distance, - final IntegerValue p_orientation, IntegerValue p_latitude, - IntegerValue p_longitude) { -// //TERFactory.getInstance().logDebug( -// "ItsExternalFunctionsProvider", -// "fx_computePositionUsingDistance", -// String.format("%d, %d", p_distance.getInteger(), -// p_orientation.getInteger())); - - FloatValue v_distance = _tcicdWrapper.getFloat(); - v_distance.setFloat(p_distance.getFloat()); - double angularD = new Double(v_distance.getFloat()) / earthRadius; - double radHeading = new Double(_tcicdWrapper.getInteger(p_orientation)) * Math.PI / 180; - - // Convert to rad - double lat1 = (new Double(_tcicdWrapper.getInteger(p_refLatitude)) / 10000000) * Math.PI / 180; - double long1 = (new Double(_tcicdWrapper.getInteger(p_refLongitude)) / 10000000) * Math.PI / 180; - - double lat2 = Math.asin(Math.sin(lat1) * Math.cos(angularD) - + Math.cos(lat1) * Math.sin(angularD) * Math.cos(radHeading)); - double long2 = long1 - + Math.atan2( - Math.sin(radHeading) * Math.sin(angularD) - * Math.cos(lat1), - Math.cos(angularD) - Math.sin(lat1) * Math.sin(lat2)); - - // normalise to -180...+180 - long2 = (long2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI; - - // convert to 1/10 of microdegrees - Long rlat2 = Math.round(lat2 * 10000000 / Math.PI * 180); - Long rlong2 = Math.round(long2 * 10000000 / Math.PI * 180); - - // The out parameter needs to be set on the object level - _tcicdWrapper.setInteger(p_latitude, rlat2.intValue()); - _tcicdWrapper.setInteger(p_longitude, rlong2.intValue()); -// p_latitude = _tcicdWrapper.setInteger((int) rlat2); -// p_longitude = _tcicdWrapper.setInteger((int) rlong2); - - } // End of method fx_computePositionUsingDistance - - /** - * External function to compute a position using a rotation - * - * @param p_iutLongPosVector - * Reference position - * @param p_rotation - * Rotation value (in degrees) - * @param p_latitude - * Computed position's latitude - * @param p_longitude - * Computed position's longitude - * - * TTCN-3 signature: external function - * fx_computePositionFromRotation(in LongPosVector - * p_iutLongPosVector, in Int32 - * p_rotation, out Int32 p_latitude, out Int32 p_longitude); - * @remark See http://www.movable-type.co.uk/scripts/latlong.html - */ - @Override - public synchronized void fx_computePositionFromRotation( - final IntegerValue p_refLatitude, - final IntegerValue p_refLongitude, - final IntegerValue p_cenLatitude, - final IntegerValue p_cenLongitude, - final IntegerValue p_rotation, - IntegerValue p_latitude, - IntegerValue p_longitude) { - //TERFactory.getInstance().logDebug( -// "ItsExternalFunctionsProvider", -// "fx_computePositionFromRotation", -// String.format("%d", p_rotation.getFloat())); - // 1. Compute distance between the 2 points - double lat1 = Math.toRadians((double)_tcicdWrapper.getInteger(p_cenLatitude) / 10000000.0); - double long1 = Math.toRadians((double)_tcicdWrapper.getInteger(p_cenLongitude) / 10000000.0); - double lat2 = Math.toRadians((double)_tcicdWrapper.getInteger(p_refLatitude) / 10000000.0); - double long2 = Math.toRadians((double)_tcicdWrapper.getInteger(p_refLongitude) / 10000000.0); - double dlat = lat2 - lat1; - double dlong = long2 - long1; - double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlong / 2) * Math.sin(dlong / 2); - double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - //double d = earthRadius * c; - //TERFactory.getInstance().logDebug("fx_computePositionFromRotation: Angular distance = " + c); - - // 2. Compute bearing - double y = Math.sin(long2 - long1) * Math.cos(lat2); - double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(long2 - long1); - double brng = Math.atan2(y, x); - //TERFactory.getInstance().logDebug("fx_computePositionFromRotation: Bearing = " + Math.toDegrees(brng)); - - // 3. Compute distance between the 2 points - double rotation = Math.toRadians((double)_tcicdWrapper.getInteger(p_rotation) / 10.0) + brng; - //TERFactory.getInstance().logDebug("fx_computePositionFromRotation = rotation: " + Math.toDegrees(rotation)); - double lat = Math.asin(Math.sin(lat1) * Math.cos(c) + Math.cos(lat1) * Math.sin(c) * Math.cos(rotation)); - double long_ = long1 + Math.atan2(Math.sin(rotation) * Math.sin(c)*Math.cos(lat1), Math.cos(c) - Math.sin(lat1) * Math.sin(lat)); - - // 4. Normalize - // normalise to -180...+180 - long_ = (long_ + 3 * Math.PI) % (2 * Math.PI) - Math.PI; - - // The out parameter needs to be set on the object level - Long rlat = Math.round(Math.toDegrees(lat) * 10000000); - Long rlong = Math.round(Math.toDegrees(long_) * 10000000); - _tcicdWrapper.setInteger(p_latitude, rlat.intValue()); - _tcicdWrapper.setInteger(p_longitude, rlong.intValue()); - //TERFactory.getInstance().logDebug("Lat = " + p_latitude.getInteger() + " - long = " + p_longitude.getInteger()); - } // End of method fx_computePositionFromRotation - - @Override - public FloatValue fx_computeRadiusFromCircularArea(FloatValue p_squareMeters) { - - // Initialise the returned value - FloatValue radius = _tcicdWrapper.getFloat(); - - radius.setFloat((float) Math.sqrt(p_squareMeters.getFloat() / Math.PI)); - - return radius; - } - - /** - * External function to compute timestamp based on current time - * - * @return Unix-Epoch-Time mod 2^32 - * - * TTCN-3 signature: external function fx_computeGnTimestamp() - * return UInt32; - */ - @Override - public IntegerValue fx_computeGnTimestamp() { - - IntegerValue timestamp = _tcicdWrapper.setInteger( - new BigInteger( - 1, - ByteHelper.longToByteArray((System.currentTimeMillis() - ITS_REF_TIME) % (long)Math.pow(2,32), Long.SIZE / Byte.SIZE) - ) - ); - - return timestamp; - } - - /** - * @desc Calculate ICMPv6 checksum on pseudo header according RFC 4443 - - * Clause 2.3 - * @param p_sourceAddress - * Source address (128 bits), - * @param p_destinationAddress - * Destination address (128 bits) - * @param p_payloadLength - * Upper-Layer Packet Length (32 bits) - * @param p_payload - * Upper-Layer payload - * @param p_nextHdr - * Next header value (e.g. 0x3a for ICMPv6) (8bits) - * @return The checksum value (16bits) - * @see RFC 2460 IPv6 Specification - * - * TTCN-3 signature: external function fx_computeIPv6CheckSum( in - * template (value) Ipv6Address p_sourceAddress, in template (value) - * Ipv6Address p_destinationAddress, in template (value) integer - * p_payloadLength, in template (value) octetstring p_payload, in - * template (value) integer p_nextHdr ) return Oct2; - * - *
-     * Pseudo header is defined by RFC 2460 - Clause 8.1
-     *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
-     *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-     *  |                                                               |
-     *  +                                                               +
-     *  |                                                               |
-     *  +                         Source Address                        +
-     *  |                                                               |
-     *  +                                                               +
-     *  |                                                               |
-     *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-     *  |                                                               |
-     *  +                                                               +
-     *  |                                                               |
-     *  +                      Destination Address                      +
-     *  |                                                               |
-     *  +                                                               +
-     *  |                                                               |
-     *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-     *  |                   Upper-Layer Packet Length                   |
-     *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-     *  |                      zero                     |  Next Header  |
-     *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-     * 
- */ - @Override - public OctetstringValue fx_computeIPv6CheckSum( - final OctetstringValue p_sourceAddress, - final OctetstringValue p_destinationAddress, - final IntegerValue p_payloadLength, - final OctetstringValue p_payload, final IntegerValue p_nextHdr) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_computeIPv6CheckSum"); - - // Build the pseudo header according RFC 2460 - Clause 8.1 - ByteArrayOutputStream pseudoheader = new ByteArrayOutputStream(); - // Source address (128bits) - int i = 0; - for (; i < p_sourceAddress.getLength(); i++) { - pseudoheader.write(p_sourceAddress.getOctet(i)); - } // End of 'for' loop - // Destination address (128bits) - for (i = 0; i < p_destinationAddress.getLength(); i++) { - pseudoheader.write(p_destinationAddress.getOctet(i)); - } // End of 'for' loop - try { - // Upper-Layer Packet Length (32bits) - pseudoheader.write(ByteHelper.intToByteArray(_tcicdWrapper.getInteger(p_payloadLength), 4)); - // Checksum set to 0 (24bits) - pseudoheader.write(ByteHelper.intToByteArray(0, 3)); - // Next header (8bits) - pseudoheader.write((byte) _tcicdWrapper.getInteger(p_nextHdr)); - } catch (IOException e) { - e.printStackTrace(); - } - // Add the payload - for (i = 0; i < p_payload.getLength(); i++) { - pseudoheader.write(p_payload.getOctet(i)); - } // End of 'for' loop - - i = 0; - int length = pseudoheader.size(); - byte[] buffer = pseudoheader.toByteArray(); - ByteHelper - .dump("ItsExternalFunctionsProvider.fx_computeIPv6CheckSum: pseaudo header", - buffer); - long sum = 0; - while (length > 0) { - sum += (buffer[i++] & 0xff) << 8; - if ((--length) == 0) { - break; - } - sum += (buffer[i++] & 0xff); - --length; - } - sum = (~((sum & 0xFFFF) + (sum >> 16))) & 0xFFFF; - //TERFactory.getInstance().logDebug(String.format("ItsExternalFunctionsProvider.fx_computeIPv6CheckSum: finalSum=%d",sum)); - // Set the return value - OctetstringValue checksum = _tcicdWrapper.getOctetstring(); - checksum.setLength(2); - checksum.setOctet(0, (byte) ((byte) (sum >> 8) & 0xff)); - checksum.setOctet(1, (byte) (sum & 0x00ff)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_computeIPv6CheckSum", checksum); // FIXME Check which method to call for logging - return checksum; - } - - @Override - public OctetstringValue xf_parseIpv6Address( - CharstringValue p_textIpv6Address) { - - byte[] hexIpv6Address = null; - - try { - InetAddress ipv6Address = InetAddress.getByName(p_textIpv6Address - .getString()); - hexIpv6Address = ipv6Address.getAddress(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - - OctetstringValue result = _tcicdWrapper.getOctetstring(); - result.setLength(hexIpv6Address.length); - for (int i = 0; i < hexIpv6Address.length; i++) { - result.setOctet(i, hexIpv6Address[i]); - } - return result; - } - - /** - * @desc Produces a 256-bit (32-byte) hash value - * @param p_toBeHashedData Data to be used to calculate the hash value - * @return The hash value - */ - public OctetstringValue fx_hashWithSha256(final OctetstringValue p_toBeHashedData) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_hashWithSha256"); - - byte[] toBeHashedData = new byte[p_toBeHashedData.getLength()]; - for (int i = 0; i < toBeHashedData.length; i++) { - toBeHashedData[i] = (byte) p_toBeHashedData.getOctet(i); - } // End 'for' statement - byte[] hash = CryptoLib.hashWithSha256(toBeHashedData); - - OctetstringValue result = _tcicdWrapper.getOctetstring(); - result.setLength(hash.length); - for (int i = 0; i < hash.length; i++) { - result.setOctet(i, hash[i]); - } // End 'for' statement - return result; - } - - /** - * @desc Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signaturee - * @param p_toBeSignedData The data to be signed - * @param p_privateKey The private key - * @return The signature value - */ - public OctetstringValue fx_signWithEcdsaNistp256WithSha256(final OctetstringValue p_toBeSignedData, final OctetstringValue/*IntegerValue*/ p_privateKey) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_signWithEcdsaNistp256WithSha256"); - - byte[] toBeSignedData = new byte[p_toBeSignedData.getLength()]; - for (int i = 0; i < toBeSignedData.length; i++) { - toBeSignedData[i] = (byte) p_toBeSignedData.getOctet(i); - } // End 'for' statement - byte[] privateKey = new byte[p_privateKey.getLength()]; - for (int i = 0; i < privateKey.length; i++) { - privateKey[i] = (byte) p_privateKey.getOctet(i); - } // End 'for' statement - byte[] signed; - try { -// TERFactory.getInstance().logDebug("fx_signWithEcdsaNistp256WithSha256: toBeSignedData=" + ByteHelper.byteArrayToString(toBeSignedData) + " - " + toBeSignedData.length); -// TERFactory.getInstance().logDebug("fx_signWithEcdsaNistp256WithSha256: ts103097SignatureEncodedAsByteArray=" + new BigInteger(privateKey)); - signed = CryptoLib.signWithEcdsaNistp256WithSha256(toBeSignedData, new BigInteger(privateKey)); - } catch (Exception e) { - e.printStackTrace(); - signed = new byte[] {}; - } - - OctetstringValue result = _tcicdWrapper.getOctetstring(); - result.setLength(signed.length); - for (int i = 0; i < signed.length; i++) { - result.setOctet(i, signed[i]); - } // End 'for' statement - return result; - } - - /** - * @desc Verify the signature of the specified data - * @param p_toBeVerifiedData The data to be verified - * @param p_signature The signature - * @param p_ecdsaNistp256PublicKeyX The public key (x coordinate) - * @param p_ecdsaNistp256PublicKeyY The public key (y coordinate) - * @return true on success, false otherwise - */ - public BooleanValue fx_verifyWithEcdsaNistp256WithSha256(final OctetstringValue p_toBeVerifiedData, final OctetstringValue p_signature, final OctetstringValue p_ecdsaNistp256PublicKeyX, final OctetstringValue p_ecdsaNistp256PublicKeyY) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_verifyWithEcdsaNistp256WithSha256"); - - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(false); - - byte[] toBeVerifiedData = new byte[p_toBeVerifiedData.getLength()]; - for (int i = 0; i < toBeVerifiedData.length; i++) { - toBeVerifiedData[i] = (byte) p_toBeVerifiedData.getOctet(i); - } // End 'for' statement - byte[] ts103097SignatureEncodedAsByteArray = new byte[p_signature.getLength()]; - for (int i = 0; i < ts103097SignatureEncodedAsByteArray.length; i++) { - ts103097SignatureEncodedAsByteArray[i] = (byte) p_signature.getOctet(i); - } // End 'for' statement - byte[] ecdsaNistp256PublicKeyX = new byte[p_ecdsaNistp256PublicKeyX.getLength()]; - for (int i = 0; i < ecdsaNistp256PublicKeyX.length; i++) { - ecdsaNistp256PublicKeyX[i] = (byte) p_ecdsaNistp256PublicKeyX.getOctet(i); - } // End 'for' statement - byte[] ecdsaNistp256PublicKeyY = new byte[p_ecdsaNistp256PublicKeyY.getLength()]; - for (int i = 0; i < ecdsaNistp256PublicKeyY.length; i++) { - ecdsaNistp256PublicKeyY[i] = (byte) p_ecdsaNistp256PublicKeyY.getOctet(i); - } // End 'for' statement - try { -// TERFactory.getInstance().logDebug("fx_verifyWithEcdsaNistp256WithSha256: toBeVerifiedData=" + ByteHelper.byteArrayToString(toBeVerifiedData) + " - " + toBeVerifiedData.length); -// TERFactory.getInstance().logDebug("fx_verifyWithEcdsaNistp256WithSha256: ts103097SignatureEncodedAsByteArray=" + ByteHelper.byteArrayToString(ts103097SignatureEncodedAsByteArray)); -// TERFactory.getInstance().logDebug("fx_verifyWithEcdsaNistp256WithSha256: ecdsaNistp256PublicKeyX=" + ByteHelper.byteArrayToString(ecdsaNistp256PublicKeyX)); -// TERFactory.getInstance().logDebug("fx_verifyWithEcdsaNistp256WithSha256: ecdsaNistp256PublicKeyY=" + ByteHelper.byteArrayToString(ecdsaNistp256PublicKeyY)); - boolean ret = CryptoLib.verifyWithEcdsaNistp256WithSha256(toBeVerifiedData, ts103097SignatureEncodedAsByteArray, ecdsaNistp256PublicKeyX, ecdsaNistp256PublicKeyY); - result.setBoolean(ret); - } catch (Exception e) { - e.printStackTrace(); - } - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_verifyWithEcdsaNistp256WithSha256"); - return result; - } - - /** - * @desc Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm - * @param p_privateKey The new private key value - * @param p_publicKeyX The new public key value (x coordinate) - * @param p_publicKeyX The new public key value (y coordinate) - * @return true on success, false otherwise - */ - public BooleanValue fx_generateKeyPair(OctetstringValue/*IntegerValue*/ p_privateKey, OctetstringValue p_publicKeyX, OctetstringValue p_publicKeyY) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_generateKeyPair"); - - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(true); - - EcdsaP256KeyPair ecdsaP256KeyPair = CryptoLib.generateKeyPair(); - byte[] ref = ecdsaP256KeyPair.getPrivateKey().toByteArray(); - p_privateKey.setLength(ref.length); - for (int i = 0; i < p_privateKey.getLength(); i++) { - p_privateKey.setOctet(i, ref[i]); - } // End 'for' statement - ref = ecdsaP256KeyPair.getPublicKeyX(); - p_publicKeyX.setLength(ref.length); - for (int i = 0; i < ref.length; i++) { - p_publicKeyX.setOctet(i, ref[i]); - } // End 'for' statement - ref = ecdsaP256KeyPair.getPublicKeyY(); - p_publicKeyY.setLength(ref.length); - for (int i = 0; i < ref.length; i++) { - p_publicKeyY.setOctet(i, ref[i]); - } // End 'for' statement - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_generateKeyPair"); - return result; - } - - /** - * @desc Check that given polygon doesn't have neither self-intersections nor holes. - * @param p_region Polygonal Region - * @return true on success, false otherwise - */ - public BooleanValue fx_isValidPolygonalRegion(final RecordOfValue p_region) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isValidPolygonalRegion"); - - // Setup arguments - ArrayList polygonalArea = new ArrayList(); - for (int position = 0; position < p_region.getLength(); position++) { - RecordValue rv = (RecordValue) p_region.getField(position); - polygonalArea.add( - new WGS84( - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - )); - } // End of 'for' statement - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isValidPolygonArea(polygonalArea)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isValidPolygonalRegion"); - return result; - } - - @Override - public BooleanValue fx_isPolygonalRegionInside(final RecordOfValue p_parent, final RecordOfValue p_region) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isPolygonalRegionInside"); - - // Setup arguments - ArrayList parentArea = new ArrayList(); - for (int position = 0; position < p_parent.getLength(); position++) { - RecordValue rv = (RecordValue) p_parent.getField(position); - parentArea.add( - new WGS84( - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - )); - } // End of 'for' statement - ArrayList regionArea = new ArrayList(); - for (int position = 0; position < p_region.getLength(); position++) { - RecordValue rv = (RecordValue) p_region.getField(position); - regionArea.add( - new WGS84( - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - )); - } // End of 'for' statement - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isPolygonalRegionInside(parentArea, regionArea)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isPolygonalRegionInside"); - return result; - } - - @Override - public BooleanValue fx_isLocationInsideCircularRegion(final RecordValue p_region, final RecordValue p_location) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideCircularRegion"); - - // Setup arguments - RecordValue rv = (RecordValue)p_region.getField("center"); // Center - WGS84 center = new WGS84( - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - ); - int radius = _tcicdWrapper.getInteger((IntegerValue)p_region.getField("radius")); - WGS84 location = new WGS84( // Location - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("longitude"))) - ); - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isLocationInsideCircularArea(location, center, radius)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideCircularRegion"); - return result; - } - - @Override - public BooleanValue fx_isLocationInsideRectangularRegion(final RecordOfValue p_region, final RecordValue p_location) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideRectangularRegion"); - - // Setup arguments - ArrayList< ArrayList > polygonalAreas = new ArrayList< ArrayList >(); - for (int position = 0; position < p_region.getLength(); position++) { - RecordValue rectangleArea = (RecordValue)p_region.getField(position); - // Retrieve corners - RecordValue rv = (RecordValue)rectangleArea.getField("northwest"); // Upper left corner - WGS84 upperLeftCorner = new WGS84( - (long)_tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - (long)_tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - ); - rv = (RecordValue)rectangleArea.getField("southeast"); // Lower right corner - WGS84 lowerRightCorner = new WGS84( - (long)_tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - (long) _tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - ); - // Build the polygonal area - ArrayList rectangularItem = new ArrayList(); - rectangularItem.add(upperLeftCorner); - rectangularItem.add( - new WGS84( - upperLeftCorner.getLatitude(), - lowerRightCorner.getLongitude(), - lowerRightCorner.getAltitude() - ) - ); - rectangularItem.add(lowerRightCorner); - rectangularItem.add( - new WGS84( - lowerRightCorner.getLatitude(), - upperLeftCorner.getLongitude(), - upperLeftCorner.getAltitude() - ) - ); - - polygonalAreas.add(rectangularItem); - } // End of 'for' statement - - WGS84 location = new WGS84( // Location - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("longitude"))) - ); - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isLocationInsidePolygonalAreas(location, polygonalAreas)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideRectangularRegion"); - return result; - } - - @Override - public BooleanValue fx_isLocationInsidePolygonalRegion(final RecordOfValue p_region, final RecordValue p_location) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsidePolygonalRegion"); - - // Setup arguments - ArrayList polygonalArea = new ArrayList(); - for (int position = 0; position < p_region.getLength(); position++) { - RecordValue rv = (RecordValue) p_region.getField(position); - polygonalArea.add( - new WGS84( - (long)_tcicdWrapper.getInteger((IntegerValue)(rv.getField("latitude"))), - (long)_tcicdWrapper.getInteger((IntegerValue)(rv.getField("longitude"))) - )); - } // End of 'for' statement - WGS84 location = new WGS84( // Location - (long)_tcicdWrapper.getInteger((IntegerValue)(p_location.getField("latitude"))), - (long)_tcicdWrapper.getInteger((IntegerValue)(p_location.getField("longitude"))) - ); - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isLocationInsidePolygonalArea(location, polygonalArea)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsidePolygonalRegion"); - return result; - } - - @Override - public BooleanValue fx_isLocationInsideIdentifiedRegion(final RecordValue p_region, final RecordValue p_location) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideIdentifiedRegion"); - - // Setup arguments - int regionDictionary = ((EnumeratedValue) p_region.getField("region_dictionary")).getInt(); - int regionId = _tcicdWrapper.getInteger((IntegerValue)(p_region.getField("region_identifier"))); - long localRegion = _tcicdWrapper.getBigInteger((IntegerValue)(p_region.getField("local_region"))); - WGS84 location = new WGS84( // Location - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("latitude"))), - _tcicdWrapper.getInteger((IntegerValue)(p_location.getField("longitude"))) - ); - - // Call Geodesic function - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(Positioning.getInstance().isLocationInsideIdentifiedRegion(regionDictionary, regionId, localRegion, location)); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_isLocationInsideIdentifiedRegion"); - return result; - } - - @Override - public FloatValue fx_dms2dd(final IntegerValue p_degrees, final IntegerValue p_minutes, final FloatValue p_seconds, final OctetstringValue p_latlon) { - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_dms2dd"); - - // Call Geodesic function - FloatValue result = _tcicdWrapper.getFloat(); - DMS location = new DMS( // Location - _tcicdWrapper.getInteger(p_degrees), - _tcicdWrapper.getInteger(p_minutes), - p_seconds.getFloat(), - (char)p_latlon.getOctet(0) - ); - result.setFloat((float) location.toDD()); - - //TERFactory.getInstance().logDebug("ItsExternalFunctionsProvider", "fx_dms2dd"); - return result; - } - - /** - * @desc Load in memory cache the certificates available in the specified directory - * @param p_rootDirectory Root directory to access to the certificates identified by the certificate ID - * @param p_configId A configuration identifier - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_loadCertificates(final CharstringValue p_rootDirectory, final CharstringValue p_configId) { - - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(_certCache.loadCertificates(p_rootDirectory.getString(), p_configId.getString())); - - return result; - } - - /** - * @desc Unload from memory cache the certificates - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_unloadCertificates() { - - BooleanValue result = _tcicdWrapper.getBoolean(); - result.setBoolean(_certCache.unloadCertificates()); - - return result; - } - - /** - * @desc Read the specified certificate - * @param p_certificateId the certificate identifier - * @param p_certificate the expected certificate - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_readCertificate(final CharstringValue p_certificateId, OctetstringValue p_certificate) { - - BooleanValue result = _tcicdWrapper.getBoolean(); - ByteArrayOutputStream certificate = new ByteArrayOutputStream(); - boolean b = _certCache.readCertificate(p_certificateId.getString(), certificate); - result.setBoolean(b); - - if(b){ - byte[] value = certificate.toByteArray(); - p_certificate.setLength(value.length); - if (value.length != 0) { - for (int i = 0; i < value.length; i++) { - p_certificate.setOctet(i, value[i]); - } // End 'for' statement - } - }else{ - p_certificate.setLength(0); - } - - return result; - } - - private static final byte[] ZERO32 = new byte[] { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - - - /** - * @desc Read the specified certificate digest - * @param p_certificateId the certificate identifier - * @param p_digest the expected certificate digest - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_readCertificateDigest(final CharstringValue p_certificateId, OctetstringValue p_digest) { - - BooleanValue result = _tcicdWrapper.getBoolean(); - ByteArrayOutputStream digest = new ByteArrayOutputStream(); - boolean b = _certCache.readCertificateDigest(p_certificateId.getString(), digest); - result.setBoolean(b); - - p_digest.setLength(8); - byte[] value; - if(b){ - value = digest.toByteArray(); - if (value.length != 8) { - value = ZERO32; - } - }else{ - value = ZERO32; - } - for (int i = 0; i < 8; i++) { - p_digest.setOctet(i, value[i]); - } // End 'for' statement - return result; - } - - /** - * @desc Read the signing private key for the specified certificate - * @param p_keysId the keys identifier - * @param p_key the signing private key - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_readSigningKey(CharstringValue p_keysId, OctetstringValue p_key) { - - BooleanValue result = _tcicdWrapper.getBoolean(); - ByteArrayOutputStream key = new ByteArrayOutputStream(); - - boolean b = _certCache.readSigningKey(p_keysId.getString(), key); - result.setBoolean(b); - - p_key.setLength(32); - - byte[] value; - if(b){ - value = key.toByteArray(); - if(value.length != 32) { - value = ZERO32; - } - }else{ - value = ZERO32; - } - for (int i = 0; i < 32; i++) { - p_key.setOctet(i, value[i]); - } - return result; - } - - /** - * @desc Read the encrypting private key for the specified certificate - * @param p_keysId the keys identifier - * @param p_key the encrypting private key - * @return true on success, false otherwise - */ - @Override - public BooleanValue fx_readEncryptingKey(CharstringValue p_keysId, OctetstringValue p_key) { - - BooleanValue result = _tcicdWrapper.getBoolean(); - ByteArrayOutputStream key = new ByteArrayOutputStream(); - - boolean b = _certCache.readEncryptingKey(p_keysId.getString(), key); - result.setBoolean(b); - - p_key.setLength(32); - - byte[] value; - if(b){ - value = key.toByteArray(); - if(value.length != 32) { - value = ZERO32; - } - }else{ - value = ZERO32; - } - for (int i = 0; i < 32; i++) { - p_key.setOctet(i, value[i]); - } - return result; - } - -} // End of class ExternalFunctions - diff --git a/javasrc/geodesic/org/etsi/geodesic/CountriesAreas.java b/javasrc/geodesic/org/etsi/geodesic/CountriesAreas.java deleted file mode 100644 index dacead1def0abbd51a4950e4e5cf5a5b69dbdd0d..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/CountriesAreas.java +++ /dev/null @@ -1,464 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.geodesic; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.etsi.adapter.TERFactory; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; - - -public class CountriesAreas implements ICountriesAreas { - - /** - * Unique reference to this object - */ - private static ICountriesAreas Instance; - - /** - * The ISO-3166-1 region dictionary identifier - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.25 IdentifiedRegion - */ - private final int Iso_3166_1 = 0; - - /** - * The United Nations region dictionary identifier - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.25 IdentifiedRegion - */ - private final int Un_stats = 1; - - /** - * Reference to the Google JSon parser - */ - private JsonParser _jsonParser = null; - - /** - * Conversion from UN to ISO-3166 numerical code - * @see http://unstats.un.org/unsd/methods/m49/m49alphaf.htm - */ - private Map _un2iso3611; - - /** - * Conversion from ISO-3166 numerical code to alpha-2 code - * @see http://fr.wikipedia.org/wiki/ISO_3166-1 - */ - private Map _in2str4iso3611; - - /** - * Polygon areas for each country referenced by ISO 3166 - */ - private Map>> _countriesPolygons; - - /** - * Singleton pattern implementation - */ - public static ICountriesAreas getInstance() { - if (Instance == null) { - Instance = new CountriesAreas(); - Instance.initialise(); - } - - return Instance; - } - - private CountriesAreas() { - super(); - - _jsonParser = new JsonParser(); - - _countriesPolygons = new HashMap>>(); - - _in2str4iso3611 = new HashMap(); - _in2str4iso3611.put(new Integer(4), "AF"); - _in2str4iso3611.put(new Integer(8), "AL"); - _in2str4iso3611.put(new Integer(10), "AQ"); - _in2str4iso3611.put(new Integer(12), "DZ"); - _in2str4iso3611.put(new Integer(16), "AS"); - _in2str4iso3611.put(new Integer(20), "AD"); - _in2str4iso3611.put(new Integer(24), "AO"); - _in2str4iso3611.put(new Integer(28), "AG"); - _in2str4iso3611.put(new Integer(31), "AZ"); - _in2str4iso3611.put(new Integer(32), "AR"); - _in2str4iso3611.put(new Integer(36), "AU"); - _in2str4iso3611.put(new Integer(40), "AT"); - _in2str4iso3611.put(new Integer(44), "BS"); - _in2str4iso3611.put(new Integer(48), "BH"); - _in2str4iso3611.put(new Integer(50), "BD"); - _in2str4iso3611.put(new Integer(51), "AM"); - _in2str4iso3611.put(new Integer(52), "BB"); - _in2str4iso3611.put(new Integer(56), "BE"); - _in2str4iso3611.put(new Integer(60), "BM"); - _in2str4iso3611.put(new Integer(64), "BT"); - _in2str4iso3611.put(new Integer(68), "BO"); - _in2str4iso3611.put(new Integer(70), "BA"); - _in2str4iso3611.put(new Integer(72), "BA"); - _in2str4iso3611.put(new Integer(74), "BV"); - _in2str4iso3611.put(new Integer(76), "BR"); - _in2str4iso3611.put(new Integer(84), "BZ"); - _in2str4iso3611.put(new Integer(86), "IO"); - _in2str4iso3611.put(new Integer(90), "SB"); - _in2str4iso3611.put(new Integer(92), "VG"); - _in2str4iso3611.put(new Integer(96), "BN"); - _in2str4iso3611.put(new Integer(100), "BG"); - _in2str4iso3611.put(new Integer(104), "MM"); - _in2str4iso3611.put(new Integer(108), "BI"); - _in2str4iso3611.put(new Integer(112), "BY"); - _in2str4iso3611.put(new Integer(116), "KH"); - _in2str4iso3611.put(new Integer(120), "CM"); - _in2str4iso3611.put(new Integer(124), "CA"); - _in2str4iso3611.put(new Integer(132), "CV"); - _in2str4iso3611.put(new Integer(136), "CY"); - _in2str4iso3611.put(new Integer(140), "CF"); - _in2str4iso3611.put(new Integer(144), "LK"); - _in2str4iso3611.put(new Integer(148), "TD"); - _in2str4iso3611.put(new Integer(152), "CL"); - _in2str4iso3611.put(new Integer(156), "CN"); - _in2str4iso3611.put(new Integer(158), "TW"); - _in2str4iso3611.put(new Integer(162), "CX"); - _in2str4iso3611.put(new Integer(166), "CC"); - _in2str4iso3611.put(new Integer(170), "CO"); - _in2str4iso3611.put(new Integer(174), "KM"); - _in2str4iso3611.put(new Integer(175), "YT"); - _in2str4iso3611.put(new Integer(178), "CG"); - _in2str4iso3611.put(new Integer(180), "CD"); - _in2str4iso3611.put(new Integer(184), "CK"); - _in2str4iso3611.put(new Integer(188), "CR"); - _in2str4iso3611.put(new Integer(191), "HR"); - _in2str4iso3611.put(new Integer(192), "CU"); - _in2str4iso3611.put(new Integer(196), "CY"); - _in2str4iso3611.put(new Integer(203), "CZ"); - _in2str4iso3611.put(new Integer(204), "BJ"); - _in2str4iso3611.put(new Integer(208), "DK"); - _in2str4iso3611.put(new Integer(212), "DM"); - _in2str4iso3611.put(new Integer(214), "DO"); - _in2str4iso3611.put(new Integer(218), "EC"); - _in2str4iso3611.put(new Integer(222), "SV"); - _in2str4iso3611.put(new Integer(226), "GQ"); - _in2str4iso3611.put(new Integer(231), "ET"); - _in2str4iso3611.put(new Integer(232), "ER"); - _in2str4iso3611.put(new Integer(233), "EE"); - _in2str4iso3611.put(new Integer(234), "FO"); - _in2str4iso3611.put(new Integer(238), "FK"); - _in2str4iso3611.put(new Integer(239), "GS"); - _in2str4iso3611.put(new Integer(242), "FJ"); - _in2str4iso3611.put(new Integer(246), "FI"); - _in2str4iso3611.put(new Integer(248), "AX"); - _in2str4iso3611.put(new Integer(250), "FR"); - _in2str4iso3611.put(new Integer(254), "GF"); - _in2str4iso3611.put(new Integer(258), "PF"); - _in2str4iso3611.put(new Integer(260), "TF"); - _in2str4iso3611.put(new Integer(262), "DJ"); - _in2str4iso3611.put(new Integer(266), "GA"); - _in2str4iso3611.put(new Integer(268), "GE"); - _in2str4iso3611.put(new Integer(270), "GM"); - _in2str4iso3611.put(new Integer(275), "PS"); - _in2str4iso3611.put(new Integer(276), "DE"); - _in2str4iso3611.put(new Integer(288), "GH"); - _in2str4iso3611.put(new Integer(292), "GI"); - _in2str4iso3611.put(new Integer(296), "KI"); - _in2str4iso3611.put(new Integer(300), "GR"); - _in2str4iso3611.put(new Integer(304), "GL"); - _in2str4iso3611.put(new Integer(308), "GD"); - _in2str4iso3611.put(new Integer(312), "GP"); - _in2str4iso3611.put(new Integer(316), "GU"); - _in2str4iso3611.put(new Integer(320), "GT"); - _in2str4iso3611.put(new Integer(324), "GI"); - _in2str4iso3611.put(new Integer(328), "GY"); - _in2str4iso3611.put(new Integer(332), "HT"); - _in2str4iso3611.put(new Integer(334), "HM"); - _in2str4iso3611.put(new Integer(336), "VA"); - _in2str4iso3611.put(new Integer(340), "HN"); - _in2str4iso3611.put(new Integer(344), "HK"); - _in2str4iso3611.put(new Integer(348), "HU"); - _in2str4iso3611.put(new Integer(352), "IS"); - _in2str4iso3611.put(new Integer(356), "IN"); - _in2str4iso3611.put(new Integer(360), "ID"); - _in2str4iso3611.put(new Integer(364), "IR"); - _in2str4iso3611.put(new Integer(368), "IR"); - _in2str4iso3611.put(new Integer(372), "IE"); - _in2str4iso3611.put(new Integer(376), "IL"); - _in2str4iso3611.put(new Integer(380), "IT"); - _in2str4iso3611.put(new Integer(384), "CI"); - _in2str4iso3611.put(new Integer(388), "JM"); - _in2str4iso3611.put(new Integer(392), "JP"); - _in2str4iso3611.put(new Integer(398), "KZ"); - _in2str4iso3611.put(new Integer(400), "JO"); - _in2str4iso3611.put(new Integer(404), "KE"); - _in2str4iso3611.put(new Integer(408), "KP"); - _in2str4iso3611.put(new Integer(410), "KR"); - _in2str4iso3611.put(new Integer(414), "KW"); - _in2str4iso3611.put(new Integer(417), "KG"); - _in2str4iso3611.put(new Integer(418), "LA"); - _in2str4iso3611.put(new Integer(422), "LB"); - _in2str4iso3611.put(new Integer(426), "LS"); - _in2str4iso3611.put(new Integer(428), "LV"); - _in2str4iso3611.put(new Integer(430), "LR"); - _in2str4iso3611.put(new Integer(434), "LY"); - _in2str4iso3611.put(new Integer(438), "LI"); - _in2str4iso3611.put(new Integer(440), "LT"); - _in2str4iso3611.put(new Integer(442), "LU"); - _in2str4iso3611.put(new Integer(446), "MO"); - _in2str4iso3611.put(new Integer(450), "MG"); - _in2str4iso3611.put(new Integer(454), "MW"); - _in2str4iso3611.put(new Integer(458), "MY"); - _in2str4iso3611.put(new Integer(462), "MV"); - _in2str4iso3611.put(new Integer(466), "ML"); - _in2str4iso3611.put(new Integer(470), "MT"); - _in2str4iso3611.put(new Integer(474), "MQ"); - _in2str4iso3611.put(new Integer(478), "MR"); - _in2str4iso3611.put(new Integer(480), "MU"); - _in2str4iso3611.put(new Integer(484), "MX"); - _in2str4iso3611.put(new Integer(492), "MC"); - _in2str4iso3611.put(new Integer(496), "MN"); - _in2str4iso3611.put(new Integer(498), "MD"); - _in2str4iso3611.put(new Integer(499), "ME"); - _in2str4iso3611.put(new Integer(500), "MS"); - _in2str4iso3611.put(new Integer(504), "MA"); - _in2str4iso3611.put(new Integer(508), "MZ"); - _in2str4iso3611.put(new Integer(512), "OM"); - _in2str4iso3611.put(new Integer(516), "NA"); - _in2str4iso3611.put(new Integer(520), "NR"); - _in2str4iso3611.put(new Integer(524), "NP"); - _in2str4iso3611.put(new Integer(528), "NL"); - _in2str4iso3611.put(new Integer(531), "CW"); - _in2str4iso3611.put(new Integer(533), "AW"); - _in2str4iso3611.put(new Integer(534), "SX"); - _in2str4iso3611.put(new Integer(535), "BQ"); - _in2str4iso3611.put(new Integer(540), "NC"); - _in2str4iso3611.put(new Integer(548), "VU"); - _in2str4iso3611.put(new Integer(554), "NZ"); - _in2str4iso3611.put(new Integer(558), "NI"); - _in2str4iso3611.put(new Integer(562), "NE"); - _in2str4iso3611.put(new Integer(566), "NG"); - _in2str4iso3611.put(new Integer(570), "NU"); - _in2str4iso3611.put(new Integer(574), "NF"); - _in2str4iso3611.put(new Integer(578), "NO"); - _in2str4iso3611.put(new Integer(580), "MP"); - _in2str4iso3611.put(new Integer(581), "UM"); - _in2str4iso3611.put(new Integer(583), "FM"); - _in2str4iso3611.put(new Integer(584), "MH"); - _in2str4iso3611.put(new Integer(585), "PW"); - _in2str4iso3611.put(new Integer(586), "PK"); - _in2str4iso3611.put(new Integer(591), "PA"); - _in2str4iso3611.put(new Integer(598), "PG"); - _in2str4iso3611.put(new Integer(600), "PY"); - _in2str4iso3611.put(new Integer(604), "PE"); - _in2str4iso3611.put(new Integer(608), "PH"); - _in2str4iso3611.put(new Integer(612), "PN"); - _in2str4iso3611.put(new Integer(616), "PL"); - _in2str4iso3611.put(new Integer(620), "PT"); - _in2str4iso3611.put(new Integer(624), "GW"); - _in2str4iso3611.put(new Integer(626), "TL"); - _in2str4iso3611.put(new Integer(630), "PR"); - _in2str4iso3611.put(new Integer(634), "QA"); - _in2str4iso3611.put(new Integer(638), "RE"); - _in2str4iso3611.put(new Integer(642), "RO"); - _in2str4iso3611.put(new Integer(643), "RU"); - _in2str4iso3611.put(new Integer(646), "RW"); - _in2str4iso3611.put(new Integer(652), "BL"); - _in2str4iso3611.put(new Integer(654), "SH"); - _in2str4iso3611.put(new Integer(659), "KN"); - _in2str4iso3611.put(new Integer(660), "AI"); - _in2str4iso3611.put(new Integer(662), "LC"); - _in2str4iso3611.put(new Integer(663), "MF"); - _in2str4iso3611.put(new Integer(666), "PM"); - _in2str4iso3611.put(new Integer(670), "VC"); - _in2str4iso3611.put(new Integer(674), "SM"); - _in2str4iso3611.put(new Integer(678), "ST"); - _in2str4iso3611.put(new Integer(682), "SA"); - _in2str4iso3611.put(new Integer(686), "SN"); - _in2str4iso3611.put(new Integer(688), "RS"); - _in2str4iso3611.put(new Integer(690), "SC"); - _in2str4iso3611.put(new Integer(694), "SL"); - _in2str4iso3611.put(new Integer(702), "SG"); - _in2str4iso3611.put(new Integer(703), "SK"); - _in2str4iso3611.put(new Integer(704), "VN"); - _in2str4iso3611.put(new Integer(705), "SI"); - _in2str4iso3611.put(new Integer(706), "SO"); - _in2str4iso3611.put(new Integer(710), "ZA"); - _in2str4iso3611.put(new Integer(716), "ZW"); - _in2str4iso3611.put(new Integer(724), "ES"); - _in2str4iso3611.put(new Integer(728), "SS"); - _in2str4iso3611.put(new Integer(729), "SD"); - _in2str4iso3611.put(new Integer(732), "EH"); - _in2str4iso3611.put(new Integer(740), "SR"); - _in2str4iso3611.put(new Integer(744), "SJ"); - _in2str4iso3611.put(new Integer(748), "SZ"); - _in2str4iso3611.put(new Integer(752), "SE"); - _in2str4iso3611.put(new Integer(756), "CH"); - _in2str4iso3611.put(new Integer(760), "SY"); - _in2str4iso3611.put(new Integer(762), "TJ"); - _in2str4iso3611.put(new Integer(764), "TH"); - _in2str4iso3611.put(new Integer(768), "TG"); - _in2str4iso3611.put(new Integer(772), "TK"); - _in2str4iso3611.put(new Integer(776), "TO"); - _in2str4iso3611.put(new Integer(780), "TT"); - _in2str4iso3611.put(new Integer(784), "AE"); - _in2str4iso3611.put(new Integer(788), "TN"); - _in2str4iso3611.put(new Integer(792), "TR"); - _in2str4iso3611.put(new Integer(795), "TM"); - _in2str4iso3611.put(new Integer(796), "TC"); - _in2str4iso3611.put(new Integer(798), "TV"); - _in2str4iso3611.put(new Integer(800), "UG"); - _in2str4iso3611.put(new Integer(804), "UA"); - _in2str4iso3611.put(new Integer(807), "MK"); - _in2str4iso3611.put(new Integer(818), "EG"); - _in2str4iso3611.put(new Integer(826), "GB"); - _in2str4iso3611.put(new Integer(831), "GG"); - _in2str4iso3611.put(new Integer(832), "JE"); - _in2str4iso3611.put(new Integer(833), "IM"); - _in2str4iso3611.put(new Integer(834), "TZ"); - _in2str4iso3611.put(new Integer(840), "US"); - _in2str4iso3611.put(new Integer(850), "VI"); - _in2str4iso3611.put(new Integer(854), "BF"); - _in2str4iso3611.put(new Integer(858), "UY"); - _in2str4iso3611.put(new Integer(860), "UZ"); - _in2str4iso3611.put(new Integer(862), "VE"); - _in2str4iso3611.put(new Integer(876), "WF"); - _in2str4iso3611.put(new Integer(882), "WS"); - _in2str4iso3611.put(new Integer(887), "YE"); - _in2str4iso3611.put(new Integer(894), "ZM"); - - _un2iso3611 = _in2str4iso3611; // Until today, both tables are identical - - } // End of constructor - - @Override - public boolean initialise() { - try { - // Load JSon countries areas and parse it - RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); - Map systemProperties = runtimeBean.getSystemProperties(); - String fileName = systemProperties.get("user.dir") + systemProperties.get("file.separator") + "ne-countries-50m.json"; - BufferedReader in = new BufferedReader(new FileReader(new File(fileName))); - StringBuilder str = new StringBuilder(); - String lineSeparator = System.getProperty("line.separator"); - String line; - while ((line = in.readLine()) != null ) { - str.append(line); - str.append(lineSeparator); - } // End of 'while' statement - try { - parseLine(str.toString()); - } catch (JsonSyntaxException e) { - e.printStackTrace(); - } - in.close(); - - return true; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return false; - } - - /** - * - * @param p_stringToParse The JSon file to parse - * @see http://geojson.org/geojson-spec.html - * @see http://ckan.it.ox.ac.uk/fr/dataset/geojson-by-country-code - */ - private void parseLine(final String p_stringToParse) { - JsonElement jelement = _jsonParser.parse(p_stringToParse); - if (jelement != null) { - JsonObject jobj = jelement.getAsJsonObject(); - if (jobj != null) { - JsonArray jarray = jobj.getAsJsonArray("features"); - for (int i = 0; i < jarray.size(); i++) { - JsonObject properties = jarray.get(i).getAsJsonObject().getAsJsonObject("properties"); - String regionId = properties.getAsJsonPrimitive("iso_a2").getAsString(); - JsonObject geometry = jarray.get(i).getAsJsonObject().getAsJsonObject("geometry"); - String type = geometry.getAsJsonPrimitive("type").getAsString(); - _countriesPolygons.put(regionId, new ArrayList>()); - if (type.equalsIgnoreCase("Polygon") ) { - ArrayList points = new ArrayList(); - JsonArray coordinates = geometry.getAsJsonArray("coordinates").get(0).getAsJsonArray(); - for (int j = 0; j < coordinates.size(); j++) { - points.add( - new WGS84( - coordinates.get(j).getAsJsonArray().get(1).getAsDouble(), - coordinates.get(j).getAsJsonArray().get(0).getAsDouble(), - 0 - ) - ); - } // End of 'for' statement - _countriesPolygons.get(regionId).add(points); - } else if (geometry.getAsJsonPrimitive("type").getAsString().equalsIgnoreCase("MultiPolygon")) { - ArrayList points = new ArrayList(); - JsonArray coordinates = geometry.getAsJsonArray("coordinates"); - for (int j = 0; j < coordinates.size(); j++) { - JsonArray subCoordinates = coordinates.get(j).getAsJsonArray(); - for (int k = 0; k < subCoordinates.size(); k++) { - JsonArray subSubCoordinates = subCoordinates.get(k).getAsJsonArray(); - for (int l = 0; l < subSubCoordinates.size(); l++) { - points.add( - new WGS84( - subSubCoordinates.get(l).getAsJsonArray().get(1).getAsDouble(), - subSubCoordinates.get(l).getAsJsonArray().get(0).getAsDouble(), - 0 - ) - ); - } // End of 'for' statement - } // End of 'for' statement - _countriesPolygons.get(regionId).add(points); - } // End of 'for' statement - } else if (geometry.getAsJsonPrimitive("type").getAsString().equalsIgnoreCase("LineString")) { - // TODO To be continued - } else if (geometry.getAsJsonPrimitive("type").getAsString().equalsIgnoreCase("MultiLineString")) { - // TODO To be continued - } - } // End of 'for' statement - } - } - } - - @Override - public boolean isLocationInsideIdentifiedRegion(final int p_regionDictionary, final int p_regionId, final long p_localRegion, final WGS84 p_location) { -// TERFactory.getInstance().logDebug(">>> CountriesAreas.isLocationInsideIdentifiedRegion: " + p_regionDictionary + ", " + p_regionId + ", " + p_localRegion + ", " + p_location); - - boolean result = false; - if (p_regionDictionary == Iso_3166_1) { - if (_in2str4iso3611.containsKey(p_regionId)) { - result = process(_in2str4iso3611.get(p_regionId), p_localRegion, p_location); - } // else, error - } else if (p_regionDictionary == Un_stats) { - if (_un2iso3611.containsKey(p_regionId)) { - result = process(_in2str4iso3611.get(p_regionId), p_localRegion, p_location); - } // else, error - } // else, error - - return result; - } - - public boolean process(final String p_regionId, final long p_localRegion, final WGS84 p_location) { -// TERFactory.getInstance().logDebug(">>> CountriesAreas.process: " + p_regionId + ", " + p_localRegion + ", " + p_location); - - if (_countriesPolygons.containsKey(p_regionId)) { - ArrayList> areas = _countriesPolygons.get(p_regionId); - return Positioning.getInstance().isLocationInsidePolygonalAreas(p_location, areas); - } - - return false; - } - -} // End of class CountriesAreas diff --git a/javasrc/geodesic/org/etsi/geodesic/DMS.java b/javasrc/geodesic/org/etsi/geodesic/DMS.java deleted file mode 100644 index 0577d90ef81d1173b2c0698c998858a1464dd6cc..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/DMS.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.geodesic; - -public class DMS { - - private int _degrees = Integer.MAX_VALUE; - - private int _minutes = Integer.MAX_VALUE; - - private double _seconds = Double.NaN; - - private char _latlon = (char)0x00; - - private double _wgs84 = Double.NaN; - - /** - * @desc Constructor - * @param p_degrees The degrees (D) - * @param p_minutes The minutes (M) - * @param p_seconds The seconds (S) - * @param p_latlon The latitude/longitude: (N|S|E|W) - */ - public DMS(final int p_degrees, final int p_minutes, final double p_seconds, final char p_latlon) { - setValue(p_degrees, p_minutes, p_seconds, p_latlon); - } // End of DMS ctor - - /** - * @desc Update location - * @param p_degrees The degrees (D) - * @param p_minutes The minutes (M) - * @param p_seconds The seconds (S) - * @param p_latlon The latitude/longitude: (N|S|E|W) - */ - public void setValue(final int p_degrees, final int p_minutes, final double p_seconds, final char p_latlon) { - _degrees = p_degrees; - _minutes = p_minutes; - _seconds = p_seconds; - _latlon = p_latlon; - - _wgs84 = - (double)p_degrees + - (double)p_minutes / 60 + - (double)p_seconds / 3600; - if ((p_latlon == 'W') || (p_latlon == 'S')) _wgs84 *= -1.0; - } - - public double toDD() { - return _wgs84; - } - -} // End of class DMS diff --git a/javasrc/geodesic/org/etsi/geodesic/ICountriesAreas.java b/javasrc/geodesic/org/etsi/geodesic/ICountriesAreas.java deleted file mode 100644 index 8b0f3caf57de2555c6af47fbca3d352a1d61ca10..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/ICountriesAreas.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.geodesic; - -public interface ICountriesAreas { - - /** - * @desc Initialise the object - * @return true on success, false otherwise - */ - public boolean initialise(); - - /** - * @desc Check if a location is inside a predefined geographic region determined by the region dictionary and the region identifier - * @param p_regionDictionary The region dictionary - * @param p_regionId The region identifier - * @param p_localRegion The whole region. 0 if the whole region is meant - * @param p_location The location to be checked - * @return true on success, false otherwise - * @see Draft ETSI TS 103 097 V1.1.14 Clause 4.2.25 IdentifiedRegion - */ - public boolean isLocationInsideIdentifiedRegion(final int p_regionDictionary, final int p_regionId, final long p_localRegion, final WGS84 p_location); - -} // End of interface ICountriesAreas diff --git a/javasrc/geodesic/org/etsi/geodesic/IPositioning.java b/javasrc/geodesic/org/etsi/geodesic/IPositioning.java deleted file mode 100644 index de87766438cc2f86195f4707e24e878b7a57db2f..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/IPositioning.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.geodesic; - -import java.util.ArrayList; - -public interface IPositioning { - - /** - * @desc Check that the location is inside an elliptic area - * @param p_location The device location - * @param p_ellipticArea The circular area to consider - * @return true on success, false otherwise - */ - public boolean isLocationInsideEllipticArea(final WGS84 p_location, final ArrayList p_ellipticArea); - - /** - * @desc Check that the location is inside a polygonal area - * @param p_location The device location - * @param p_polygonalArea The polygonal area to consider - * @return true on success, false otherwise - */ - public boolean isLocationInsidePolygonalArea(final WGS84 p_location, final ArrayList p_polygonalArea); - - /** - * @desc Check that the location is inside a list of polygonal areas - * @param p_location The device location - * @param p_polygonalAreas The list of polygonal areas to consider - * @return true on success, false otherwise - */ - public boolean isLocationInsidePolygonalAreas(final WGS84 p_location, final ArrayList< ArrayList > p_polygonalAreas); - - /** - * @desc Check that the location is inside a circular area - * @param p_region The circular area to consider - * @param p_center The circle center position - * @param p_radius The circle radius - * @return true on success, false otherwise - */ - public boolean isLocationInsideCircularArea(final WGS84 p_location, final WGS84 p_center, final int p_radius); - - /** - * @desc Check if the polygonal area is valid (neither self-intersections nor holes) - * @param p_polygonalArea The polygonal area to consider - * @return true on success, false otherwise - */ - public boolean isValidPolygonArea(final ArrayList p_polygonalArea); - - /** - * @desc Check if the location is inside an identified region - * @param p_regionDictionary - * @param p_regionId - * @param p_localRegion - * @param p_location - * @return true on success, false otherwise - */ - boolean isLocationInsideIdentifiedRegion(final int p_regionDictionary, final int p_regionId, final long p_localRegion, final WGS84 p_location); - - /** - * @desc Check if a polygonal regin is inside another one - * @param p_parent The main polygonal region - * @param p_region The polygonal region to be included - * @return true on success, false otherwise - * @verdict Unchanged - */ - public boolean isPolygonalRegionInside(final ArrayList p_parentArea, final ArrayList p_regionArea); - -} // End of interface Positioning diff --git a/javasrc/geodesic/org/etsi/geodesic/Positioning.java b/javasrc/geodesic/org/etsi/geodesic/Positioning.java deleted file mode 100644 index 714c9c0877d2e28638a6bfe9e34a0352341ec2ea..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/Positioning.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.etsi.geodesic; - -import java.util.ArrayList; - -import org.etsi.adapter.TERFactory; - -/** - * @desc - * @see To validate GPS location: http://www.gps-coordinates.net - */ -public class Positioning implements IPositioning { - - public static double TWOPI = 2 * Math.PI; - - /** - * Unique reference to this object - */ - private static IPositioning Instance; - - /** - * Singleton pattern implementation - */ - public static IPositioning getInstance() { - if (Instance == null) { - Instance = new Positioning(); - } - - return Instance; - } - - /** - * Private constructor required for Singleton pattern implementation - */ - private Positioning() { - - } - - @Override - public boolean isLocationInsideEllipticArea(final WGS84 p_location, final ArrayList p_ellipticArea) { -// TERFactory.getInstance().logDebug(">>> Positioning.isLocationInsideEllipticArea: " + p_location); - - // TODO: implement it - // Do not forget aboout passing throw 0 meridian - return false; - } - - @Override - public boolean isLocationInsidePolygonalArea(final WGS84 p_location, final ArrayList p_polygonalArea) { -// TERFactory.getInstance().logDebug(">>> Positioning.isLocationInsidePolygonalArea: " + p_location + ", " + p_polygonalArea); - - // TODO: Check passing throw 0 meridian and Equador - - double angle = 0; - int poleNum = p_polygonalArea.size(); - for (int index = 0; index < poleNum; index++) { - WGS84 delta1 = new WGS84( - p_polygonalArea.get(index).getLatitude() - p_location.getLatitude(), - p_polygonalArea.get(index).getLongitude() - p_location.getLongitude(), - 0 - ); - WGS84 delta2 = new WGS84( - p_polygonalArea.get((index + 1) % poleNum).getLatitude() - p_location.getLatitude(), - p_polygonalArea.get((index + 1) % poleNum).getLongitude() - p_location.getLongitude(), - 0 - ); - angle += calcAngle(delta1, delta2); - } // End of 'for' statement - -// TERFactory.getInstance().logDebug("<<< Positioning.isLocationInsidePolygonalArea: " + (boolean)((Math.abs(angle) < Math.PI) ? false : true)); - return (boolean)((Math.abs(angle) < Math.PI) ? false : true); - } - - @Override - public boolean isLocationInsidePolygonalAreas(final WGS84 p_location, final ArrayList< ArrayList > p_polygonalAreas) { -// TERFactory.getInstance().logDebug(">>> Positioning.isLocationInsidePolygonalAreas: " + p_location); - - for (int index = 0; index < p_polygonalAreas.size(); index++) { - if (isLocationInsidePolygonalArea(p_location, p_polygonalAreas.get(index))) { - return true; - } - } // End of 'for' statement - - return false; // Not found - } - - @Override - public boolean isLocationInsideCircularArea(final WGS84 p_location, final WGS84 p_center, final int p_radius) { -// TERFactory.getInstance().logDebug(">>> Positioning.isLocationInsideCircularArea: " + p_location + ", " + p_center + ", " + p_radius); - - // TODO: Check passing throw 0 meridian and Equador - - double theta = p_center.getLongitude() - p_location.getLongitude(); - double distance = - Math.sin(dd2rad(p_center.getLatitude())) * Math.sin(dd2rad(p_location.getLatitude())) + - Math.cos(dd2rad(p_center.getLatitude())) * Math.cos(dd2rad(p_location.getLatitude())) * Math.cos(dd2rad(theta)); - distance = rad2dd(Math.acos(distance)); - distance *= 60 * 1.1515 * 1.609344 /*Kilometers*/; -// TERFactory.getInstance().logDebug("Positioning.isLocationInsideCircularArea: distance=" + distance); - -// TERFactory.getInstance().logDebug("<<< Positioning.isLocationInsideCircularArea: " + (boolean)(distance <= (p_radius / 1000.0))); - return (boolean)(distance <= (p_radius / 1000.0)); - } - - @Override - public boolean isValidPolygonArea(final ArrayList p_polygonalArea) { -// TERFactory.getInstance().logDebug(">>> Positioning.isValidPolygonArea"); - - // Check if polygon coordinates are valid - for (int i = 0; i < p_polygonalArea.size(); i++) { - if (!p_polygonalArea.get(i).isValidPosition()) { - return false; - } - } - - return true; - } - - @Override - public boolean isLocationInsideIdentifiedRegion(final int p_regionDictionary, final int p_regionId, final long p_localRegion, final WGS84 p_location) { -// TERFactory.getInstance().logDebug(">>> Positioning.isLocationInsideIdentifiedRegion: " + p_regionDictionary + ", " + p_regionId + ", " + p_localRegion + ", " + p_location); - - return CountriesAreas.getInstance().isLocationInsideIdentifiedRegion(p_regionDictionary, p_regionId, p_localRegion, p_location); - } - - @Override - public boolean isPolygonalRegionInside(final ArrayList p_parentArea, final ArrayList p_regionArea) { -// TERFactory.getInstance().logDebug(">>> Positioning.isPolygonalRegionInside: " + p_parentArea + ", " + p_regionArea); - - for (int i = 0; i < p_regionArea.size(); i++) { - if (!isLocationInsidePolygonalArea(p_regionArea.get(i), p_parentArea)) { - return false; - } - } // End of 'for' statement - - return true; - } - - private double calcAngle(final WGS84 p_origin, final WGS84 p_end) { -// TERFactory.getInstance().logDebug(">>> calcAngle: " + p_origin.getLatitude() + " - " + p_origin.getLongitude() + " - " + p_end.getLatitude() + " - " + p_end.getLongitude()); - double theta1 = Math.atan2(p_origin.getLatitude(), p_origin.getLongitude()); -// TERFactory.getInstance().logDebug("Angle2D: theta1=" + theta1); - double theta2 = Math.atan2(p_end.getLatitude(), p_end.getLongitude()); -// TERFactory.getInstance().logDebug("Angle2D: theta2=" + theta2); - double dtheta = theta2 - theta1; -// TERFactory.getInstance().logDebug("calcAngle: dtheta" + dtheta); - while (dtheta > Math.PI) { - dtheta -= TWOPI; - } // End of 'while' statement - while (dtheta < -Math.PI) { - dtheta += TWOPI; - } // End of 'while' statement - -// TERFactory.getInstance().logDebug("<<< calcAngle: " + dtheta); - return dtheta; - } - - /** - * @desc Convert a decimal degrees value into a decimal radian - * @param p_decimalDegrees The value to convert - * @return The converted value in radians - */ - private double dd2rad(final double p_decimalDegrees) { - return p_decimalDegrees * Math.PI / 180; - } - - /** - * @desc Convert a decimal radians value into a decimal degrees - * @param p_decimalRadians The value to convert - * @return The converted value in degrees - */ - private double rad2dd(final double p_decimalRadians) { - return p_decimalRadians * 180.0 / Math.PI; - } - -} // End of class Positioning diff --git a/javasrc/geodesic/org/etsi/geodesic/WGS84.java b/javasrc/geodesic/org/etsi/geodesic/WGS84.java deleted file mode 100644 index 0944187d086a8098adae0b259634b5e4b5c86a5b..0000000000000000000000000000000000000000 --- a/javasrc/geodesic/org/etsi/geodesic/WGS84.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @author ETSI / STF481 / Yann Garcia - * @version $URL$ - * $Id$ - */ -package org.etsi.geodesic; - -public class WGS84 { - - /** Longitude of the location */ - private double _longitude = Double.NaN; - - /** Latitude of the location */ - private double _latitude = Double.NaN; - - /** Altitude of the location */ - private double _altitude = Double.NaN; - - private int _longitudeD = Integer.MAX_VALUE; - - private int _longitudeM = Integer.MAX_VALUE; - - private double _longitudeS = Double.NaN; - - private int _latitudeD = Integer.MAX_VALUE; - - private int _latitudeM = Integer.MAX_VALUE; - - private double _latitudeS = Double.NaN; - - /** Heading of the location */ -// private double _heading = Double.NaN; - - /** - * @desc Constructor - * @param p_longitude Longitude of the location - * @param p_latitude Latitude of the location - * @param p_altitude Altitude of the location - */ - public WGS84(final double p_latitude, final double p_longitude, final double p_altitude) { - setValue(p_latitude, p_longitude, p_altitude); - } // End of WGS84 ctor - - /** - * Constructor used to convert WGSLatitude/WGSLongitude value into decimal degrees value - * @param p_latitude Latiude integer value (significand length shall be 6 digits length) - * @param p_longitude Longitude integer value (significand length shall 6 digits length) - */ - public WGS84(final long p_latitude, final long p_longitude) { - setValue( - (double)p_latitude / 10000000, - (double)p_longitude / 10000000, - 0.0 - ); - } // End of WGS84 ctor - - /** - * @desc Update location - * @param p_longitude Longitude of the location - * @param p_latitude Latitude of the location - * @param p_altitude Altitude of the location - */ - public void setValue(final double p_latitude, final double p_longitude, final double p_altitude) { - _latitude = p_latitude; - _latitudeD = (int)p_latitude; // Truncate the decimals - double dv = (p_latitude - _latitudeD) * 60; - _latitudeM = (int)dv; - _latitudeS = (dv - _latitudeM) * 60; - - _longitude = p_longitude; - _longitudeD = (int)p_longitude; // Truncate the decimals - dv = (p_longitude - _longitudeD) * 60; - _longitudeM = (int)dv; - _longitudeS = (dv - _longitudeM) * 60; - - _altitude = p_altitude; - } - - public double getLongitude() { - return _longitude; - } - - public double getLatitude() { - return _latitude; - } - - public double getAltitude() { - return _altitude; - } - - public boolean isValidPosition() { - if ((_latitude > -90) && (_latitude < 90) && (_longitude > -180) && (_longitude < 180)) { - return true; - } - - return false; - } - - public String toDMS() { - return String.format("WGS84: l=%s°$s'%s'', L=%s°$s'%s'', A=%s", - String.valueOf(_latitudeD), String.valueOf(_latitudeM), String.valueOf(_latitudeS), - String.valueOf(_longitudeD), String.valueOf(_longitudeM), String.valueOf(_longitudeS), - String.valueOf(_altitude) - ); - } - - @Override - public String toString() { - return String.format("WGS84: lat=%s, lon=%s, alt=%s", String.valueOf(_latitude), String.valueOf(_longitude), String.valueOf(_altitude)); - } - -} // End of class WGS84 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/BuiltInCodec.java b/javasrc/tool/org/etsi/its/tool/elvior/BuiltInCodec.java deleted file mode 100644 index 0c7f233ab966dd04f86eb51ca03f6c20a4bb97e3..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/BuiltInCodec.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.etsi.its.tool.elvior; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.elvior.ttcn.tritci.TciProvider; -import org.elvior.ttcn.tritci.TriMessageEx; -import org.elvior.ttcn.tritci.TriProvider; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.TciCDProvided; -import org.etsi.ttcn.tci.TciDecodingResult; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class BuiltInCodec implements TciCDProvided { - - /** - * Logger instance - */ - protected final static Logger _logger = Logger.getLogger("org.etsi.its"); - - private String _encodingName; - - /** - * Constructor - */ - public BuiltInCodec(final String encodingName) { - _logger.entering("BuiltInCodec", "BuiltInCodec", encodingName); - - if (encodingName.equals("LibItsDenm_asn1")) { - _encodingName = "DENM_PDU_Descriptions"; - } else if (encodingName.equals("LibItsCam_asn1")) { - _encodingName = "CAM_PDU_Descriptions"; - } else if (encodingName.equals("LibItsMapemSpatem_asn1")) { - _encodingName = "MAPEM_SPATEM_ETSI"; - } else if (encodingName.equals("LibItsIvim_asn1")) { - _encodingName = "IVIM_PDU_Descriptions"; - } else if (encodingName.equals("LibItsEvcsn_asn1")) { - _encodingName = "EVCSN_PDU_Descriptions"; - } else if (encodingName.equals("LibItsSremSsem_asn1")) { - _encodingName = "SREM_SSEM_ETSI"; - } else if (encodingName.equals("LibItsCALMmsap_asn1")) { - _encodingName = "CALMmsap"; - } else if (encodingName.equals("LibItsCALMllsap_asn1")) { - _encodingName = "CALMllsap"; - } else if (encodingName.equals("LibItsFntp_asn1")) { - _encodingName = "CALMfntp"; - } else if (encodingName.equals("LibItsFsap_asn1")) { - _encodingName = "CALMfsap"; - } else if (encodingName.equals("LibItsIicp_asn1")) { - _encodingName = "CALMiitsscu"; - } else { - _encodingName = ""; - } - } - - /** - * This operation decodes message according to the encoding rules and returns a TTCN-3 value. - * The decodingHypothesis shall be used to determine whether the encoded value can be decoded. - * If an encoding rule is not self-sufficient, i.e. if the encoded message does not inherently - * contain its type decodingHypothesis shall be used. If the encoded value can be decoded without - * the decoding hypothesis, the distinct null value shall be returned if the type determined from - * the encoded message is not compatible with the decoding hypothesis - * - * @param message The encoded message to be decoded - * @param decodingHypothesis The hypothesis the decoding can be based on - * @return Returns the decoded value, if the value is of a compatible type as the decodingHypothesis, else the distinct value null - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.2.1 decode - */ - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("BuiltInCodec", "decode", decodingHypothesis.getName()); - - TriMessageEx msg = TriProvider.getInstance().getTriFactory().createMessageEx(); - msg.setEncodedMessage(message.getEncodedMessage()); - if (_logger.isLoggable(Level.ALL)) ByteHelper.dump("BuiltInCodec.decode: ", msg.getEncodedMessage()); - - String type = String.format("%s.%s", _encodingName, decodingHypothesis.getName()); - _logger.info("Type: " + type); - Type asnOriginalType = getTypeForName(type); - // Check which type class the decoding hypothesis is of - Value value = TciProvider.getInstance().getSystemInterface().internalDecode(msg, asnOriginalType); - _logger.exiting("BuiltInCodec", "decode", value.toString()); - return value; - } - - @Override - public TriMessage encode(final Value template) { - _logger.entering("BuiltInCodec", "encode", template.getType().getName()); - - RecordValue asn1Value = (RecordValue)template; - String type = String.format("%s.%s", _encodingName, template.getType().getName()); - _logger.info("Type: " + type); - Type asnOriginalType = getTypeForName(type); - if (asnOriginalType != null) { - RecordValue internalASNEncodecValue = (RecordValue)asnOriginalType.newInstance(); - String[] fields = internalASNEncodecValue.getFieldNames(); - for(String field: fields) { - _logger.info(String.format("Process field %s", field)); - Value fieldValue = asn1Value.getField(field); - if(fieldValue.notPresent()) { - _logger.info(String.format("Field %s was omitted", field)); - internalASNEncodecValue.setFieldOmitted(field); - } else { - _logger.info(String.format("Field %s was added", field)); - internalASNEncodecValue.setField(field, fieldValue); - } - } // End of 'for' statement - _logger.info("Call internal codec"); - TriMessage msg = TciProvider.getInstance().getSystemInterface().internalEncode(internalASNEncodecValue); - ByteHelper.dump("BuiltInCodec.encode: ", msg.getEncodedMessage()); - _logger.exiting("BuiltInCodec", "encode"); - return msg; - } - - _logger.exiting("BuiltInCodec", "encode", "null"); - return null; - } - - private Type getTypeForName(final String type) { - _logger.entering("BuiltInCodec", "getTypeForName", type); - - Type asnOriginalType = TciProvider.getInstance().getTciCDRequired().getTypeForName(type); - if (asnOriginalType == null) { // Failed with default mechanism, try with External Attributes mechanism -// type = decodingHypothesis.getName(); //FIXME External Attributes mechanism does not work - String type_ = ""; - if (type.endsWith("nfSapPrimitivesUp")) { - type_ = String.format("%s.%s", _encodingName, "NFsapPrimitivesUp"); - } else if (type.endsWith("faSapPrimitivesUp")) { - type_ = String.format("%s.%s", _encodingName, "FAsapPrimitivesUp"); - } else if (type.endsWith("mnRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MN_Request_request"); - } else if (type.endsWith("mfCommandRequest")) { - type_ = String.format("%s.%s", _encodingName, "MF_Command_request"); - } else if (type.endsWith("miCommandRequest")) { - type_ = String.format("%s.%s", _encodingName, "MI_Command_request"); - } else if (type.endsWith("miCommandConfirm")) { - type_ = String.format("%s.%s", _encodingName, "MI_Command_confirm"); - } else if (type.endsWith("miRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MI_Request_request"); - } else if (type.endsWith("miRequestConfirm")) { - type_ = String.format("%s.%s", _encodingName, "MI_Request_confirm"); - } else if (type.endsWith("miSetRequest")) { - type_ = String.format("%s.%s", _encodingName, "MI_Set_request"); - } else if (type.endsWith("miSetConfirm")) { - type_ = String.format("%s.%s", _encodingName, "MI_Set_confirm"); - } else if (type.endsWith("miGetRequest")) { - type_ = String.format("%s.%s", _encodingName, "MI_Get_request"); - } else if (type.endsWith("miGetConfirm")) { - type_ = String.format("%s.%s", _encodingName, "MI_Get_confirm"); - } if (type.endsWith("fntpNPDU")) { - type_ = String.format("%s.%s", _encodingName, "INsapPrimitivesUp"); - } - _logger.info("Type: " + type_); - asnOriginalType = TciProvider.getInstance().getTciCDRequired().getTypeForName(type_); - } - - _logger.exiting("BuiltInCodec", "getTypeForName", asnOriginalType.getName()); - return asnOriginalType; - } // End of method getTypeForName - - @Override - public TciDecodingResult decodeValue(TriMessage arg0, Type arg1, String arg2) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TriMessage encodeValue(Value arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - -} // End of class BuiltInCodec diff --git a/javasrc/tool/org/etsi/its/tool/elvior/GetValueStructure.java b/javasrc/tool/org/etsi/its/tool/elvior/GetValueStructure.java deleted file mode 100644 index aefb2a9d19f961f1a38b1194fc0b1c796de4714d..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/GetValueStructure.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.elvior.ttcn.tritci.IntegerValueEx; -import org.etsi.ttcn.tci.BitstringValue; -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.HexstringValue; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.tci.UnionValue; -import org.etsi.ttcn.tci.Value; - -public class GetValueStructure { - - static String indent = null; - static StringBuilder buffer = null; - - static public void displayValueStructure(final Value value) { - buffer = new StringBuilder(); - indent = ""; - LogValueDataStructure(value); -// TERFactory.getInstance().logDebug(buffer.toString()); - } - - static public String getValueStructure(final Value value) { - buffer = new StringBuilder(); - indent = ""; - LogValueDataStructure(value); - return buffer.toString(); - } - - static private void LogValueDataStructure(final Value value) { - if (value.notPresent()) { - buffer.append(indent + value.getClass().getName() + " : omitted" + "\n"); - return; - } - switch (value.getType().getTypeClass()) { - case TciTypeClass.BOOLEAN: { - BooleanValue bv = (BooleanValue)value; - buffer.append(indent + bv.getClass().getName() + " : " + new java.lang.Boolean(bv.getBoolean()) + " - encode : " + bv.getValueEncoding() + " - variant : " + bv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.INTEGER: { - IntegerValueEx iv = (IntegerValueEx)value; - buffer.append(indent + iv.getClass().getName() + " : " + iv.getInt64() + " - encode : " + iv.getValueEncoding() + " - variant : " + iv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.FLOAT: { - FloatValue fv = (FloatValue)value; - buffer.append(indent + fv.getClass().getName() + " : " + fv.getFloat() + " - encode : " + fv.getValueEncoding() + " - variant : " + fv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.CHARSTRING: { - CharstringValue csv = (CharstringValue)value; - buffer.append(indent + csv.getClass().getName() + " : " + csv.getString() + " - encode : " + csv.getValueEncoding() + " - variant : " + csv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.BITSTRING: { - BitstringValue bv = (BitstringValue)value; - buffer.append(indent + bv.getClass().getName() + " : " + bv.getString() + " - encode : " + bv.getValueEncoding() + " - variant : " + bv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.OCTETSTRING: { - OctetstringValue ov = (OctetstringValue)value; - buffer.append(indent + ov.getClass().getName() + " : " + ov.getString() + " - encode : " + ov.getValueEncoding() + " - variant : " + ov.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.HEXSTRING: { - HexstringValue hv = (HexstringValue)value; - buffer.append(indent + hv.getClass().getName() + " : " + hv.getString() + " - encode : " + hv.getValueEncoding() + " - variant : " + hv.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.ENUMERATED: { - EnumeratedValue ev = (EnumeratedValue)value; - buffer.append(indent + ev.getClass().getName() + " : " + ev.getEnum() + " - encode : " + ev.getValueEncoding() + " - variant : " + ev.getValueEncodingVariant() + "\n"); - } - break; - case TciTypeClass.SET: - // No break; - case TciTypeClass.RECORD: { - RecordValue rv = (RecordValue)value; - buffer.append(indent + rv.getClass().getName() + " - encode : " + rv.getValueEncoding() + " - variant : " + rv.getValueEncodingVariant() + "\n"); - indent += "\t"; - for (String key : rv.getFieldNames()) { - LogValueDataStructure(rv.getField(key)); - } // End of 'for'statement - indent = indent.substring(0, indent.length() -1); - } - break; - case TciTypeClass.ANYTYPE: - // No break; - case TciTypeClass.UNION: { - UnionValue uv = (UnionValue)value; - buffer.append(indent + uv.getClass().getName() + " - encode : " + uv.getValueEncoding() + " - variant : " + uv.getValueEncodingVariant() + "\n"); - indent += "\t"; - LogValueDataStructure(uv.getVariant(uv.getPresentVariantName())); - indent = indent.substring(0, indent.length() -1); - } - break; - case TciTypeClass.RECORD_OF: - // No break; - case TciTypeClass.SET_OF: { - RecordOfValue rofv = (RecordOfValue)value; - buffer.append(indent + rofv.getClass().getName() + " - encode : " + rofv.getValueEncoding() + " : " + rofv.getLength() + " - variant : " + rofv.getValueEncodingVariant() + "\n"); - indent += "\t"; - for (int key = 0; key < rofv.getLength(); key++) { - LogValueDataStructure(rofv.getField(key)); - } // End of 'for'statement - indent = indent.substring(0, indent.length() -1); - } - break; - default: - throw new RuntimeException("Unimplemented class type: " + value.getType().getTypeClass()); - } // End of 'switch' value - } - -} diff --git a/javasrc/tool/org/etsi/its/tool/elvior/Its_CodecProvider.java b/javasrc/tool/org/etsi/its/tool/elvior/Its_CodecProvider.java deleted file mode 100644 index 83ec06abf9a364bdc63bfe88550598e643e91388..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/Its_CodecProvider.java +++ /dev/null @@ -1,258 +0,0 @@ -package org.etsi.its.tool.elvior; - -import java.io.IOException; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.elvior.ttcn.tritci.ChannelEventHandler; -import org.elvior.ttcn.tritci.TciProvider; -import org.elvior.ttcn.tritci.TriTciChannel; -import org.etsi.codec.ITCIRequired; -import org.etsi.codec.ITciCDWrapper; -import org.etsi.codec.TciCDWrapperFactory; -import org.etsi.tool.elvior.TciCDWrapper; -import org.etsi.ttcn.codec.CodecFactory; -import org.etsi.ttcn.tci.TciCDProvided; -import org.etsi.ttcn.tci.TciDecodingResult; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -public class Its_CodecProvider implements TciCDProvided, ChannelEventHandler, ITCIRequired { - - private static Properties _properties = new Properties(); - - /** - * Logger instance - */ - private final static Logger _logger = Logger.getLogger("org.etsi.its"); - - private ITciCDWrapper _cdReq; - - private CodecFactory _cf; - - public Its_CodecProvider() { - //_logger.entering("Its_CodecProvider", "Its_CodecProvider"); - - // Load Codec settings - _cdReq = null; - _cf = null; - try { - _properties.load(MainCodec.class.getResourceAsStream("/org/etsi/its/tool/elvior/res/codec.properties")); - } catch (IOException e) { - e.printStackTrace(); - } - String debugLevel = _properties.getProperty("DEBUG_ENABLED", "OFF"); - Level level = Level.OFF; - if (debugLevel.equalsIgnoreCase("ALL")) { - level = Level.ALL; - } else if (debugLevel.equalsIgnoreCase("INFO")) { - level = Level.INFO; - } else if (debugLevel.equalsIgnoreCase("SEVERE")) { - level = Level.SEVERE; - } else if (!debugLevel.equalsIgnoreCase("OFF")) { - // FIXME - //TERFactory.getInstance().logError("Unsupported logging level: " + debugLevel); - level = Level.OFF; - } - //_logger.addHandler(new ConsoleHandler()); - //_logger.setLevel(level); - //_logger.getHandlers()[0].setLevel(level); - - // Register this object as the instance implementing the TCI-CD Provided interface - TciProvider.getInstance().setTciCDProvided(this); - TriTciChannel channel = TriTciChannel.getInstance(); - // Set application name that will be displayed in the TestCast log - channel.setApplicationName("ItsCodec"); - // Register this object as the receiver of events generated by TestCast framework - channel.setEventHandler(this); - - initializeCodecs(); - } - - private void initializeCodecs() { - TciCDWrapperFactory.getInstance().setImpl(new TciCDWrapper()); - _cdReq = TciCDWrapperFactory.getTciCDInstance(); - - // Register External codecs - _cf = CodecFactory.getInstance(); - // TODO Reuse Build-in codec here - - String[] asn1Codecs = _properties.getProperty("ASN.1Codecs", "").split(","); - for (String codec : asn1Codecs) { - String[] paths = _properties.getProperty(codec, "").split(","); - try { - _cf.setExternalCodec(paths[0], (TciCDProvided) Class.forName(paths[1]).newInstance()); - } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - e.printStackTrace(); - } - } // End of 'for' loop - try { // This comes with 'with encode () "UpperTester"' for all UtxxxTrigger/UtxxxUpdate messages - _cf.setExternalCodec("per-basic-unaligned:1997", LibIts_asn1.class.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - public void run() { - //_logger.entering("Its_CodecProvider", "run"); - - // Attempt to connect to TestCast - if (TriTciChannel.getInstance().open()) { - try { - synchronized(this) { - wait(); - } - } catch (InterruptedException e) { - } - } - - //_logger.exiting("Its_CodecProvider", "run"); - } - - @Override - public void onConnectionClosed() { - //_logger.entering("Its_CodecProvider", "onConnectionClosed"); - synchronized(this) { - notify(); - } - } - - @Override - public void onConnectionEstablished() { - //_logger.entering("Its_CodecProvider", "onConnectionEstablished"); - } - - @Override - public void onError(String error) { - //_logger.entering("Its_CodecProvider", "onError", error); - } - - @Override - public Value decode(TriMessage message, Type decodingHypothesis) { - /*_logger.entering( - "decode", - String.format("%s - %s - %s", - decodingHypothesis.getName(), - decodingHypothesis.getTypeEncoding(), - decodingHypothesis.getTypeClass()));*/ - String encodingName = decodingHypothesis.getTypeEncoding(); - if (encodingName != null) { - encodingName = decodingHypothesis.getDefiningModule().getModuleName(); - } else { // Use basic codec - encodingName = ""; - } - TciCDProvided codec = getCodec(encodingName); - if (codec == null) { - return null; - } - Value value = codec.decode(message, decodingHypothesis); - //_logger.exiting("Its_CodecProvider.decode", (value != null) ? GetValueStructure.getValueStructure(value) : "(null)"); - return value; - } - - @Override - public TriMessage encode(Value value) { - /*_logger.entering( - "encode", - String.format( - ">>> encode: %s - %s - %s - %s - %s - %s - %s - %s - %s", - value.getType().getName(), - value.getType().getDefiningModule(), - value.getType().getDefiningModule().getModuleName(), - value.getType().getTypeExtension(), - value.getType().getTypeEncoding(), - value.getType().getTypeEncodingVariant(), - value.getValueEncoding(), - value.getValueEncodingVariant(), - (value.notPresent() == true) ? "true" : "false" - ) - );*/ -// TERFactory.getInstance().logDebug(">>> encode: " + value.getType().getName()); - String encodingName = value.getType().getTypeEncoding(); - if ((encodingName != null) && !encodingName.startsWith("Lib")) { - encodingName = value.getType().getDefiningModule().getModuleName(); - } else if (encodingName == null) { // Use basic codec - encodingName = ""; - } - TciCDProvided codec = getCodec(encodingName); - if (codec == null) { - return null; - } - //_logger.info("Value to encode: " + GetValueStructure.getValueStructure(value)); - TriMessage res = codec.encode(value); - //_logger.exiting("encode", res.toString()); - return res; - } - - /** - * This method provides the codec associated to the specified encoding identifier - * - * @param rb TTwb Runtime reference - * @param encodingName The name of the encoding, specified by the TTCN-3 key words 'with/encode' - * @return The codec associated to the specified encoding identifier - */ - @Override - public TciCDProvided getCodec(final String encodingName) { - // FIXME Remove argument here and in the interface ITCIRequired - return new Codec(); - } - - private class Codec implements TciCDProvided { - - @Override - public Value decode(TriMessage message, Type decodingHypothesis) { - //_logger.entering("Codec", "decode", decodingHypothesis.getName()); - - org.etsi.ttcn.codec.MainCodec codec = new org.etsi.ttcn.codec.MainCodec(_cdReq); - Value v = null; - try { - v = codec.triDecode(message, decodingHypothesis); - } - catch(Exception e) { - e.printStackTrace(); - } - return v; - } - - @Override - public TriMessage encode(Value value) { - //_logger.entering("Codec", "encode"); - - org.etsi.ttcn.codec.MainCodec codec = new org.etsi.ttcn.codec.MainCodec(_cdReq); - TriMessage m = null; - try { - m = codec.triEncode(value); - } - catch(Exception e) { - e.printStackTrace(); - } - return m; - } - - @Override - public TciDecodingResult decodeValue(TriMessage message, Type decodingHypothesis, String arg2) { - return TciProvider.getInstance().getTciFactory().createDecodingResult(0, decode(message, decodingHypothesis)); - } - - @Override - public TriMessage encodeValue(Value value, String arg1) { - return encode(value); - } - } - - @Override - public TciDecodingResult decodeValue(TriMessage message, Type decodingHypothesis, String arg2) { - return TciProvider.getInstance().getTciFactory().createDecodingResult(0, decode(message, decodingHypothesis)); - } - - @Override - public TriMessage encodeValue(Value value, String arg1) { - return encode(value); - } - -} // End of class Its_CodecProvider diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMllsap_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMllsap_asn1.java deleted file mode 100644 index 707e0da5e6314a93d4fa316f4f534c496af16aa5..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMllsap_asn1.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; - -public class LibItsCALMllsap_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsCALMllsap_asn1() { - _logger.entering("LibItsCALMllsap_asn1", "LibItsCALMllsap_asn1"); - _encodingName = "CALMllsap"; - } - - protected Type getTypeForName(final String type) { - _logger.entering("LibItsCALMllsap_asn1", "getTypeForName", type); - - String type_ = type; - if (type.endsWith("mnRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MN_Request_request"); - } else if (type.endsWith("msgIn_in")) { - type_ = String.format("%s.%s", _encodingName, "INsapPrimitivesDown"); - } - - Type asnOriginalType = super.getTypeForName(type_); - - _logger.exiting("LibItsCALMllsap_asn1", "getTypeForName", asnOriginalType.getName()); - return asnOriginalType; - } // End of method getTypeForName - -} // End of class LibItsCALMllsap_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMmsap_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMmsap_asn1.java deleted file mode 100644 index cc3e1265e70039844320ad72524ecbfedb99e768..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCALMmsap_asn1.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; - -public class LibItsCALMmsap_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsCALMmsap_asn1() { - _logger.entering("LibItsCALMmsap_asn1", "LibItsCALMmsap_asn1"); - _encodingName = "CALMmsap"; - } - - protected Type getTypeForName(final String type) { - _logger.entering("LibItsCALMmsap_asn1", "getTypeForName", type); - - String type_ = type; - if (type.endsWith("mfRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MF_Request_request"); - } else if (type.endsWith("mnRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MN_Request_request"); - } else if (type.endsWith("miRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MI_Request_request"); - } else if (type.endsWith("mf_Command_request")) { - type_ = String.format("%s.%s", _encodingName, "MF_Command_request"); - } else if (type.endsWith("mn_Command_request")) { - type_ = String.format("%s.%s", _encodingName, "MN_Command_request"); - } else if (type.endsWith("mi_Command_request")) { - type_ = String.format("%s.%s", _encodingName, "MI_Command_request"); - } else if (type.endsWith("faSapPrimitivesUp")) { - type_ = String.format("%s.%s", _encodingName, "FAsapPrimitivesUp"); - } - - Type asnOriginalType = super.getTypeForName(type_); - - _logger.exiting("LibItsCALMmsap_asn1", "getTypeForName", asnOriginalType.getName()); - return asnOriginalType; - } // End of method getTypeForName - -} // End of class LibItsCALMmsap_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCam_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsCam_asn1.java deleted file mode 100644 index f1d46ad23b637cfe0fc928bba5172aae11e3b685..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsCam_asn1.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsCam_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsCam_asn1() { - _logger.entering("LibItsCam_asn1", "LibItsCam_asn1"); - _encodingName = "CAM_PDU_Descriptions"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsCam_asn1", "decode", decodingHypothesis.getName()); - - if (decodingHypothesis.getName().endsWith("camPacket")) { - Type type = getTypeForName("CAM_PDU_Descriptions.CAM"); - return super.decode(message, type); - } - - return super.decode(message, decodingHypothesis); - } - -} // End of class LibItsCam_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsContainer_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsContainer_asn1.java deleted file mode 100644 index bb6010a250ea408b92eec8635aff078ba477fddb..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsContainer_asn1.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.elvior.ttcn.tritci.TriProvider; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsContainer_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsContainer_asn1() { - //_logger.entering("LibItsContainer_asn1", "LibItsContainer_asn1"); - _encodingName = "ITS_Container"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - //_logger.entering("LibItsContainer_asn1", "decode", decodingHypothesis.getName()); - - Value value = null; - if (decodingHypothesis.getName().equals("TimestampIts")) { - int ival = ByteHelper.byteArrayToInt(message.getEncodedMessage()); - long lval = ((long)ival) << 6; - TriMessage msg = TriProvider.getInstance().getTriFactory().createMessage(); - msg.setEncodedMessage(ByteHelper.longToByteArray(lval, 6)); - value = super.decode(msg, decodingHypothesis); - } else if (decodingHypothesis.getName().equals("TimeMark")) { - TriMessage msg1 = TriProvider.getInstance().getTriFactory().createMessage(); - msg1.setEncodedMessage(message.getEncodedMessage()); - value = super.decode(msg1, decodingHypothesis); - } else { - value = super.decode(message, decodingHypothesis); - } - - //_logger.exiting("LibIts_asn1", "decode", value.toString()); - return value; - } - -} // End of class LibItsContainer_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsDenm_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsDenm_asn1.java deleted file mode 100644 index d43121b4cd147a66d5108eaf4ebdd271d0552c87..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsDenm_asn1.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsDenm_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsDenm_asn1() { - _logger.entering("LibItsDenm_asn1", "LibItsDenm_asn1"); - _encodingName = "DENM_PDU_Descriptions"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsDenm_asn1", "decode", decodingHypothesis.getName()); - - if (decodingHypothesis.getName().endsWith("denmPacket")) { - Type type = getTypeForName("DENM_PDU_Descriptions.DENM"); - return super.decode(message, type); - } - - return super.decode(message, decodingHypothesis); - } - -} // End of class LibItsDenm_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsEvcsn_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsEvcsn_asn1.java deleted file mode 100644 index 27145b388ddb7f0077c5de94bdc564f791c3f262..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsEvcsn_asn1.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsEvcsn_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsEvcsn_asn1() { - _logger.entering("LibItsEvcsn_asn1", "LibItsEvcsn_asn1"); - _encodingName = "EVCSN_PDU_Descriptions"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsEvcsn_asn1", "decode", decodingHypothesis.getName()); - - if (decodingHypothesis.getName().endsWith("evcsnPacket")) { - Type type = getTypeForName("EVCSN_PDU_Descriptions.EvcsnPdu"); - return super.decode(message, type); - } - - return super.decode(message, decodingHypothesis); - } - -} // End of class LibItsEvcsn_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsFntp_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsFntp_asn1.java deleted file mode 100644 index 5810e8e45b8446c7083157b535f44a327433e523..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsFntp_asn1.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; - -public class LibItsFntp_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsFntp_asn1() { - _logger.entering("LibItsFntp_asn1", "LibItsFntp_asn1"); - _encodingName = "CALMfntp"; - } - - protected Type getTypeForName(final String type) { - _logger.entering("LibItsFntp_asn1", "getTypeForName", type); - - String type_ = type; - if (type.endsWith("nfSapPrimitivesUp")) { - type_ = String.format("%s.%s", _encodingName, "NFsapPrimitivesUp"); - } else if (type.endsWith("mnRequestRequest")) { - type_ = String.format("%s.%s", _encodingName, "MN_Request_request"); - } else if (type.endsWith("msgIn_nf")) { - type_ = String.format("%s.%s", _encodingName, "NFsapPrimitivesDown"); - } - - Type asnOriginalType = super.getTypeForName(type_); - - _logger.exiting("LibItsFntp_asn1", "getTypeForName", asnOriginalType.getName()); - return asnOriginalType; - } // End of method getTypeForName - -} // End of class LibItsFntp_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsFsap_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsFsap_asn1.java deleted file mode 100644 index f7307f6d7411b1c6c7582dff6a7777c4252160b4..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsFsap_asn1.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.etsi.its.tool.elvior; - -public class LibItsFsap_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsFsap_asn1() { - _logger.entering("LibItsFsap_asn1", "LibItsFsap_asn1"); - _encodingName = "CALMfsap"; - } - -} // End of class LibItsFsap_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsIicp_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsIicp_asn1.java deleted file mode 100644 index 7b0744bcc7f9d80937cc8afd883746fbd1f78fcd..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsIicp_asn1.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; - -public class LibItsIicp_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsIicp_asn1() { - _logger.entering("LibItsIicp_asn1", "LibItsIicp_asn1"); - _encodingName = "CALMiitsscu"; - } - - protected Type getTypeForName(final String type) { - _logger.entering("LibItsIicp_asn1", "getTypeForName", type); - - String type_ = type; - if (type.endsWith("msg_req")) { - type_ = String.format("%s.%s", _encodingName, "IIC_Request"); - } else if (type.endsWith("msg_resp")) { - type_ = String.format("%s.%s", _encodingName, "IIC_Response"); - } else if (type.endsWith("mcmdRq")) { - type_ = String.format("%s.%s", _encodingName, "McmdRq"); - } - - Type asnOriginalType = super.getTypeForName(type_); - - _logger.exiting("LibItsIicp_asn1", "getTypeForName", asnOriginalType.getName()); - return asnOriginalType; - } // End of method getTypeForName - -} // End of class LibItsIicp_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsIvim_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsIvim_asn1.java deleted file mode 100644 index 34e6ee75b70e33bb4896ffd4156009b4ac502ccf..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsIvim_asn1.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsIvim_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsIvim_asn1() { - _logger.entering("LibItsIvim_asn1", "LibItsIvim_asn1"); - _encodingName = "IVIM_PDU_Descriptions"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsIvim_asn1", "decode", decodingHypothesis.getName()); - - if (decodingHypothesis.getName().endsWith("ivimPacket")) { - Type type = getTypeForName("IVIM_PDU_Descriptions.IVIM"); - return super.decode(message, type); - } - - return super.decode(message, decodingHypothesis); - } - -} // End of class LibItsIvim_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsMapemSpatem_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsMapemSpatem_asn1.java deleted file mode 100644 index c66b6ae99246c78e52643f2aad5944be82e074e1..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsMapemSpatem_asn1.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsMapemSpatem_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsMapemSpatem_asn1() { - _logger.entering("LibItsMapemSpatem_asn1", "LibItsMapemSpatem_asn1"); - _encodingName = "MAPEM_SPATEM_ETSI"; - } - - @Override - public TriMessage encode(final Value template) { - _logger.entering("LibItsMapemSpatem_asn1", "encode", template.getType().getName()); - - TriMessage result; - String type = String.format("%s.%s", _encodingName, template.getType().getName()); - if (template.getType().getName().endsWith("MAPEM")) { - _encodingName = "MAPEM_PDU_Descriptions"; - result = super.encode(template); - } else { - _encodingName = "SPATEM_PDU_Descriptions"; - result = super.encode(template); - } - _encodingName = "MAPEM_SPATEM_ETSI"; - - return result; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsMapemSpatem_asn1", "decode", decodingHypothesis.getName()); - - Value result; - if (decodingHypothesis.getName().endsWith("MAPEM")) { - Type type = getTypeForName("MAPEM_PDU_Descriptions.MAPEM"); - _encodingName = "MAPEM_PDU_Descriptions"; - result = super.decode(message, type); - } else { - Type type = getTypeForName("SPATEM_PDU_Descriptions.SPATEM"); - _encodingName = "SPATEM_PDU_Descriptions"; - result = super.decode(message, type); - } - _encodingName = "MAPEM_SPATEM_ETSI"; - - return result; - } - -} // End of class LibItsMapemSpatem_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibItsSremSsem_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibItsSremSsem_asn1.java deleted file mode 100644 index bf78554ad765ffb18e2fd204d05523a8a112d985..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibItsSremSsem_asn1.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.etsi.its.tool.elvior; - -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibItsSremSsem_asn1 extends LibIts_asn1 { - - /** - * Constructor - */ - public LibItsSremSsem_asn1() { - _logger.entering("LibItsSremSsem_asn1", "LibItsSremSsem_asn1"); - _encodingName = "SREM_SSEM_ETSI"; - } - - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - _logger.entering("LibItsSremSsem_asn1", "decode", decodingHypothesis.getName()); - - if (decodingHypothesis.getName().endsWith("SREM")) { - Type type = getTypeForName("SREM_PDU_Descriptions.SREM"); - return super.decode(message, type); - } else { - Type type = getTypeForName("SSEM_PDU_Descriptions.SSEM"); - return super.decode(message, type); - } - } - - @Override - public TriMessage encode(final Value template) { - _logger.entering("LibItsSremSsem_asn1", "encode", template.getType().getName()); - - TriMessage result; - String type = String.format("%s.%s", _encodingName, template.getType().getName()); - if (template.getType().getName().endsWith("SREM")) { - _encodingName = "SREM_PDU_Descriptions"; - result = super.encode(template); - } else { - _encodingName = "SREM_PDU_Descriptions"; - result = super.encode(template); - } - _encodingName = "SREM_SSEM_ETSI"; - - return result; - } - -} // End of class LibItsSremSsem_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/LibIts_asn1.java b/javasrc/tool/org/etsi/its/tool/elvior/LibIts_asn1.java deleted file mode 100644 index b8bf4a79931274905440d83afa722cb0cf1652b1..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/LibIts_asn1.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.etsi.its.tool.elvior; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.elvior.ttcn.tritci.IntegerValueEx; -import org.elvior.ttcn.tritci.TciProvider; -import org.elvior.ttcn.tritci.TriMessageEx; -import org.elvior.ttcn.tritci.TriProvider; -import org.etsi.common.ByteHelper; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.TciCDProvided; -import org.etsi.ttcn.tci.TciDecodingResult; -import org.etsi.ttcn.tci.TciTypeClass; -import org.etsi.ttcn.tci.Type; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriMessage; - -/** - * - * Note that "Enable Internal Codec" field shall be set to true - * - */ -public class LibIts_asn1 implements TciCDProvided { - - /** - * Logger instance - */ - protected final static Logger _logger = Logger.getLogger("org.etsi.its"); - - protected String _encodingName; - - /** - * Constructor - */ - public LibIts_asn1() { - //_logger.entering("LibIts_asn1", "LibIts_asn1"); - _encodingName = ""; - } - - /** - * This operation decodes message according to the encoding rules and returns a TTCN-3 value. - * The decodingHypothesis shall be used to determine whether the encoded value can be decoded. - * If an encoding rule is not self-sufficient, i.e. if the encoded message does not inherently - * contain its type decodingHypothesis shall be used. If the encoded value can be decoded without - * the decoding hypothesis, the distinct null value shall be returned if the type determined from - * the encoded message is not compatible with the decoding hypothesis - * - * @param message The encoded message to be decoded - * @param decodingHypothesis The hypothesis the decoding can be based on - * @return Returns the decoded value, if the value is of a compatible type as the decodingHypothesis, else the distinct value null - * - * See ETSI ES 201 873-6 V4.2.1 - 7.3.2.2.1 decode - */ - @Override - public Value decode(final TriMessage message, final Type decodingHypothesis) { - //_logger.entering("LibIts_asn1", "decode", decodingHypothesis.getName()); - - TriMessageEx msg = TriProvider.getInstance().getTriFactory().createMessageEx(); - msg.setEncodedMessage(message.getEncodedMessage()); - //if (_logger.isLoggable(Level.ALL)) ByteHelper.dump("LibIts_asn1.decode: ", msg.getEncodedMessage()); - //ByteHelper.dump("LibIts_asn1.decode: ", msg.getEncodedMessage()); - String type = ""; - System.out.println("decode: " + String.format("%s.%s: %02x", decodingHypothesis.getTypeEncoding(), decodingHypothesis.getName(), message.getEncodedMessage()[1])); - if (decodingHypothesis.getTypeEncoding().equals("per-basic-unaligned:1997")) { - switch (message.getEncodedMessage()[1]) { // messageID INTEGER{ denm(1), cam(2), poi(3), spatem(4), mapem(5), ivim(6), ev-rsr(7), tistpgtransaction(8), srem(9), ssem(10), evcsn(11) } (0..255), -- Mantis #7209, #7005 - case (byte)0x01: - if (decodingHypothesis.getName().equals("DENM")) { - type = "DENM_PDU_Descriptions.DENM"; - } - break; - case (byte)0x02: - if (decodingHypothesis.getName().equals("CAM")) { - type = "CAM_PDU_Descriptions.CAM"; - } - break; - case (byte)0x05: - if (decodingHypothesis.getName().equals("MAPEM")) { - type = "MAPEM_PDU_Descriptions.MAPEM"; - } - break; - case (byte)0x04: - if (decodingHypothesis.getName().equals("SPATEM")) { - type = "SPATEM_PDU_Descriptions.SPATEM"; - } - break; - case (byte)0x06: - if (decodingHypothesis.getName().equals("IVIM")) { - type = "IVIM_PDU_Descriptions.IVIM"; - } - break; - case (byte)0x07: - if (decodingHypothesis.getName().equals("EvcsnPdu")) { - type = "EVCSN_PDU_Descriptions.EvcsnPdu"; - } - break; - case (byte)0x09: - if (decodingHypothesis.getName().equals("SREM")) { - type = "SREM_PDU_Descriptions.SREM"; - } - break; - case (byte)0x0a: - if (decodingHypothesis.getName().equals("SSEM")) { - type = "SSEM_PDU_Descriptions.SSEM"; - } - break; - default: - // Nothing to do - System.out.println("Default: " + String.format("%s.%s", decodingHypothesis.getTypeEncoding(), decodingHypothesis.getName())); - } // End of 'switch' statement - } else { - type = String.format("%s.%s", _encodingName, decodingHypothesis.getName()); - } - //_logger.info("Type: " + type); - //System.out.println("Type: " + type); - if (type.isEmpty()) { - return null; // Abort decoding - } - Type asnOriginalType = getTypeForName(type); - // Check which type class the decoding hypothesis is of - //_logger.info("asnOriginalType: " + asnOriginalType.getName()); - Value value = TciProvider.getInstance().getSystemInterface().internalDecode(msg, asnOriginalType); - //_logger.exiting("LibIts_asn1", "decode", value.toString()); - return value; - } - - @Override - public TriMessage encode(final Value template) { - //_logger.entering("LibIts_asn1", "encode", template.getType().getName()); - - String type = String.format("%s.%s", _encodingName, template.getType().getName()); - //_logger.info("Type: " + type); - Type asnOriginalType = getTypeForName(type); - if (asnOriginalType != null) { - Value internalASNEncodecValue = null; - switch (template.getType().getTypeClass()) { - case TciTypeClass.RECORD: - internalASNEncodecValue = (RecordValue)asnOriginalType.newInstance(); - String[] fields = ((RecordValue)internalASNEncodecValue).getFieldNames(); - RecordValue asn1Value = (RecordValue)template; - for(String field: fields) { - //_logger.info(String.format("Process field %s", field)); - Value fieldValue = asn1Value.getField(field); - if(fieldValue.notPresent()) { - //_logger.info(String.format("Field %s was omitted", field)); - ((RecordValue)internalASNEncodecValue).setFieldOmitted(field); - } else { - //_logger.info(String.format("Field %s was added", field)); - ((RecordValue)internalASNEncodecValue).setField(field, fieldValue); - } - } // End of 'for' statement - break; - case TciTypeClass.INTEGER: - internalASNEncodecValue = (IntegerValueEx)asnOriginalType.newInstance(); - ((IntegerValueEx)internalASNEncodecValue).setInt64(((IntegerValueEx)template).getInt64()); - break; - default: - throw new RuntimeException("Unimplemented type " + template.getType().getTypeClass()); - } // End of 'switch' statement - //_logger.info("Call internal codec"); - TriMessage msg = TciProvider.getInstance().getSystemInterface().internalEncode(internalASNEncodecValue); - //ByteHelper.dump("LibIts_asn1.encode: ", msg.getEncodedMessage()); - //_logger.exiting("LibIts_asn1", "encode"); - return msg; - } - - //_logger.exiting("LibIts_asn1", "encode", "null"); - return null; - } - - protected Type getTypeForName(final String type) { - //_logger.entering("LibIts_asn1", "getTypeForName", type); - - Type asnOriginalType = TciProvider.getInstance().getTciCDRequired().getTypeForName(type); - - //_logger.exiting("LibIts_asn1", "getTypeForName", (asnOriginalType != null) ? asnOriginalType.getName() : "(null)"); - return asnOriginalType; - } // End of method getTypeForName - - @Override - public TciDecodingResult decodeValue(TriMessage arg0, Type arg1, String arg2) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TriMessage encodeValue(Value arg0, String arg1) { - // TODO Auto-generated method stub - return null; - } - -} // End of class LibIts_asn1 diff --git a/javasrc/tool/org/etsi/its/tool/elvior/MainCodec.java b/javasrc/tool/org/etsi/its/tool/elvior/MainCodec.java deleted file mode 100644 index 050e80fc966a4b3a1bda4e00822b7d40ecf1588a..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/MainCodec.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $id$ - */ -package org.etsi.its.tool.elvior; - -public class MainCodec { - - /** - * @param args - */ - public static void main(String[] args) { - Its_CodecProvider app = new Its_CodecProvider(); - app.run(); - System.exit(0); - } - -} // End of class MainCodec diff --git a/javasrc/tool/org/etsi/its/tool/elvior/MainTA.java b/javasrc/tool/org/etsi/its/tool/elvior/MainTA.java deleted file mode 100644 index 8453e62c00db408b768b745ef1d36ab641181f25..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/MainTA.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $id$ - */ -package org.etsi.its.tool.elvior; - -public class MainTA { - - /** - * @param args - */ - public static void main(String[] args) { - PluginAdapter adapter = new PluginAdapter(); - adapter.run(); - System.exit(0); - } - -} //End of class Main diff --git a/javasrc/tool/org/etsi/its/tool/elvior/PluginAdapter.java b/javasrc/tool/org/etsi/its/tool/elvior/PluginAdapter.java deleted file mode 100644 index 0c619c43c997a30f6cb074f0de46e41c348c1bed..0000000000000000000000000000000000000000 --- a/javasrc/tool/org/etsi/its/tool/elvior/PluginAdapter.java +++ /dev/null @@ -1,1418 +0,0 @@ -/** - * @author STF 424_ITS_Test_Platform - * @version $id$ - */ -package org.etsi.its.tool.elvior; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.elvior.ttcn.tritci.ChannelEventHandler; -import org.elvior.ttcn.tritci.IntegerValueEx; -import org.elvior.ttcn.tritci.TciProvider; -import org.elvior.ttcn.tritci.TriFactory; -import org.elvior.ttcn.tritci.TriProvider; -import org.elvior.ttcn.tritci.TriTciChannel; -import org.etsi.adapter.TERFactory; -import org.etsi.codec.ITciCDWrapper; -import org.etsi.codec.TciCDWrapperFactory; -import org.etsi.common.ByteHelper; -import org.etsi.its.extfunc.IItsExternalFunctionsProvider; -import org.etsi.its.extfunc.ItsExternalFunctionsProvider; -import org.etsi.tool.elvior.TciCDWrapper; -import org.etsi.tool.elvior.TeRequiredImpl; -import org.etsi.ttcn.tci.BooleanValue; -import org.etsi.ttcn.tci.CharstringValue; -import org.etsi.ttcn.tci.EnumeratedValue; -import org.etsi.ttcn.tci.FloatValue; -import org.etsi.ttcn.tci.IntegerValue; -import org.etsi.ttcn.tci.OctetstringValue; -import org.etsi.ttcn.tci.RecordOfValue; -import org.etsi.ttcn.tci.RecordValue; -import org.etsi.ttcn.tci.TciParameterList; -import org.etsi.ttcn.tci.TciValueList; -import org.etsi.ttcn.tci.Value; -import org.etsi.ttcn.tri.TriAddress; -import org.etsi.ttcn.tri.TriAddressList; -import org.etsi.ttcn.tri.TriBoolean; -import org.etsi.ttcn.tri.TriCommunicationSA; -import org.etsi.ttcn.tri.TriCommunicationTE; -import org.etsi.ttcn.tri.TriComponentId; -import org.etsi.ttcn.tri.TriException; -import org.etsi.ttcn.tri.TriFunctionId; -import org.etsi.ttcn.tri.TriLong; -import org.etsi.ttcn.tri.TriMessage; -import org.etsi.ttcn.tri.TriParameter; -import org.etsi.ttcn.tri.TriParameterList; -import org.etsi.ttcn.tri.TriParameterPassingMode; -import org.etsi.ttcn.tri.TriPlatformPA; -import org.etsi.ttcn.tri.TriPortId; -import org.etsi.ttcn.tri.TriPortIdList; -import org.etsi.ttcn.tri.TriSignatureId; -import org.etsi.ttcn.tri.TriStatus; -import org.etsi.ttcn.tri.TriTestCaseId; -import org.etsi.ttcn.tri.TriTimerDuration; -import org.etsi.ttcn.tri.TriTimerId; -import org.etsi.ttcn.xtri.xTriCommunicationSA; - -public class PluginAdapter implements TriCommunicationSA, TriCommunicationTE, xTriCommunicationSA, TriPlatformPA, ChannelEventHandler { - /** - * This is the main PluginAdapter class - */ - private org.etsi.its.adapter.TestAdapter _itsTestAdapter; - - private static Properties _properties = new Properties(); - - /** - * Logger instance - */ - private final static Logger _logger = Logger.getLogger("org.etsi.its"); - - private TriStatus m_triOK; - - private TriStatus m_triKO; - - private IItsExternalFunctionsProvider _extfuncsImpl; - - public PluginAdapter() { - _logger.entering("PluginAdapter", "Constructor"); - - // Load TA settings - Level level = Level.ALL; - try { - _properties.load(MainTA.class.getResourceAsStream("/org/etsi/its/tool/elvior/res/ta.properties")); - String debugLevel = _properties.getProperty("DEBUG_ENABLED", "OFF"); - level = Level.OFF; - if (debugLevel.equalsIgnoreCase("ALL")) { - level = Level.ALL; - } else if (debugLevel.equalsIgnoreCase("INFO")) { - level = Level.INFO; - } else if (debugLevel.equalsIgnoreCase("SEVERE")) { - level = Level.SEVERE; - } else if (!debugLevel.equalsIgnoreCase("OFF")) { - TERFactory.getInstance().logError("Unsupported logging level: " + debugLevel); - } - } catch (IOException e) { - e.printStackTrace(); - } - _logger.addHandler(new ConsoleHandler()); - _logger.setUseParentHandlers(false); - _logger.setLevel(level); -// _logger.getHandlers()[0].setLevel(level); - - // Register this object as the instance implementing the TRI-SA interface - TriProvider.getInstance().setTriCommunicationSA(this); - // Register this object as the instance implementing the TRI-PA interface - TriProvider.getInstance().setTriPlatformPA(this); - TriTciChannel channel = TriTciChannel.getInstance(); - // Set application name that will be displayed in the TestCast log - channel.setApplicationName("ItsPlatform"); - // Register this object as the receiver of events generated by TestCast framework - channel.setEventHandler(this); - TriFactory factory = TriProvider.getInstance().getTriFactory(); - m_triOK = factory.createOkStatus(); - m_triKO = factory.createErrorStatus(); - TERFactory.setImpl(new TeRequiredImpl(this)); - // External functions - TciCDWrapperFactory.getInstance().setImpl(new TciCDWrapper()); - _extfuncsImpl = new ItsExternalFunctionsProvider(); - } - - public void run() { - _logger.entering("PluginAdapter", "run"); - - // Attempt to connect to TestCast - if (TriTciChannel.getInstance().open()) { - _itsTestAdapter = new org.etsi.its.adapter.TestAdapter(); - try { - synchronized(this) { - wait(); - } - } catch (InterruptedException e) { - } - } - _logger.exiting("PluginAdapter", "run"); - } - - public TriStatus triCall(TriComponentId componentId, TriPortId tsiPortId, - TriAddress sutAddress, TriSignatureId signatureId, - TriParameterList parameterList) { - return _itsTestAdapter.triCall(componentId, tsiPortId, sutAddress, signatureId, parameterList); - } - - public TriStatus triCallBC(TriComponentId componentId, TriPortId tsiPortId, - TriSignatureId signatureId, TriParameterList parameterList) { - return _itsTestAdapter.triCallBC(componentId, tsiPortId, signatureId, parameterList); - } - - public TriStatus triCallMC(TriComponentId componentId, TriPortId tsiPortId, - TriAddressList sutAddresses, TriSignatureId signatureId, - TriParameterList parameterList) { - return _itsTestAdapter.triCallMC(componentId, tsiPortId, sutAddresses, signatureId, parameterList); - } - - public TriStatus triEndTestCase() { - return _itsTestAdapter.triEndTestCase(); - } - - public TriStatus triExecuteTestCase(TriTestCaseId testCaseId, TriPortIdList tsiPorts) { -// TERFactory.getInstance().logDebug("triExecuteTestCase"); - // Disable XTRI functionality for all ports, so that existing SA implementation can be reused - for(int i = 0; i < tsiPorts.size(); i++) { - TriTciChannel.getInstance().enableXTriForPort(tsiPorts.get(i), false); - } - return _itsTestAdapter.triExecuteTestcase(testCaseId, tsiPorts); - } - - public TriStatus triMap(TriPortId compPortId, TriPortId tsiPortId) { -// TERFactory.getInstance().logDebug("triMap: " + compPortId.getComponent().getComponentName() + " - " + tsiPortId.getPortName()); - return _itsTestAdapter.triMap(compPortId, tsiPortId); - } - - public TriStatus triRaise(TriComponentId componentId, TriPortId tsiPortId, - TriAddress sutAddress, TriSignatureId signatureId, TriException exception) { -// TERFactory.getInstance().logDebug("triRaise"); - return _itsTestAdapter.triRaise(componentId, tsiPortId, sutAddress, signatureId, exception); - } - - public TriStatus triRaiseBC(TriComponentId componentId, - TriPortId tsiPortId, TriSignatureId signatureId, TriException exc) { -// TERFactory.getInstance().logDebug("triRaiseBC"); - return _itsTestAdapter.triRaiseBC(componentId, tsiPortId, signatureId, exc); - } - - public TriStatus triRaiseMC(TriComponentId componentId, - TriPortId tsiPortId, TriAddressList sutAddresses, - TriSignatureId signatureId, TriException exc) { -// TERFactory.getInstance().logDebug("triRaiseMC"); - return _itsTestAdapter.triRaiseMC(componentId, tsiPortId, sutAddresses, signatureId, exc); - } - - public TriStatus triReply(TriComponentId componentId, TriPortId tsiPortId, - TriAddress sutAddress, TriSignatureId signatureId, - TriParameterList parameterList, TriParameter returnValue) { -// TERFactory.getInstance().logDebug("triReply"); - return _itsTestAdapter.triReply(componentId, tsiPortId, sutAddress, signatureId, parameterList, returnValue); - } - - public TriStatus triReplyBC(TriComponentId componentId, - TriPortId tsiPortId, TriSignatureId signatureId, - TriParameterList parameterList, TriParameter returnValue) { -// TERFactory.getInstance().logDebug("triReplyBC"); - return _itsTestAdapter.triReplyBC(componentId, tsiPortId, signatureId, parameterList, returnValue); - } - - public TriStatus triReplyMC(TriComponentId componentId, - TriPortId tsiPortId, TriAddressList sutAddresses, - TriSignatureId signatureId, TriParameterList parameterList, - TriParameter returnValue) { -// TERFactory.getInstance().logDebug("triReplyMC"); - return _itsTestAdapter.triReplyMC(componentId, tsiPortId, sutAddresses, signatureId, parameterList, returnValue); - } - - public TriStatus triSAReset() { -// TERFactory.getInstance().logDebug("triSAReset"); - return _itsTestAdapter.triSAReset(); - } - - public TriStatus triSend(TriComponentId componentId, TriPortId tsiPortId, - TriAddress address, TriMessage sendMessage) { -// TERFactory.getInstance().logDebug("triSend"); - return _itsTestAdapter.triSend(componentId, tsiPortId, address, sendMessage); - } - - public TriStatus triSendBC(TriComponentId componentId, TriPortId tsiPortId, - TriMessage sendMessage) { -// TERFactory.getInstance().logDebug("triSendBC"); - return _itsTestAdapter.triSendBC(componentId, tsiPortId, sendMessage); - } - - public TriStatus triSendMC(TriComponentId componentId, TriPortId tsiPortId, - TriAddressList addresses, TriMessage sendMessage) { -// TERFactory.getInstance().logDebug("triSendMC"); - return _itsTestAdapter.triSendMC(componentId, tsiPortId, addresses, sendMessage); - } - - public TriStatus triSutActionInformal(String description) { -// TERFactory.getInstance().logDebug("triSutActionInformal"); - return _itsTestAdapter.triSutActionInformal(description); - } - - public TriStatus triUnmap(TriPortId compPortId, TriPortId tsiPortId) { -// TERFactory.getInstance().logDebug("triUnmap"); - return _itsTestAdapter.triUnmap(compPortId, tsiPortId); - } - - public TriStatus triExternalFunction(TriFunctionId functionId, TriParameterList parameterList, TriParameter returnValue) { - //TERFactory.getInstance().logDebug(">>> PluginAdapter.triExternalFunction: " + functionId.getFunctionName()); // + " - " + parameterList + " - " + returnValue.getParameterName() + " - " + returnValue.getParameterPassingMode()); - - TriStatus result = m_triOK; - if ( - functionId.getFunctionName().endsWith("fx_computeIPv6CheckSum") && - (parameterList.size() == 5) - ) { - // Calculate ICMPv6 checksum on pseudo header according RFC 4443 - Clause 2.3 - exec_computeIPv6CheckSum(parameterList, returnValue); - } else if ( - functionId.getFunctionName().endsWith("fx_computeDistance") && - (parameterList.size() == 4) - ) { - // Compute a distance between two points - exec_computeDistance(parameterList, returnValue); - } else if ( - functionId.getFunctionName().endsWith("fx_computePositionUsingDistance") && - (parameterList.size() == 6) - ) { - // Compute a position using a reference position, a distance and an orientation - exec_computePositionUsingDistance(parameterList, returnValue); - } else if ( - functionId.getFunctionName().endsWith("fx_computePositionFromRotation") && - (parameterList.size() == 7) - ) { - // Compute a reference position rotation - exec_computePositionFromRotation(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_computeGnTimestamp")) { - // Compute timestamp based on current time - exec_computeGnTimestamp(returnValue); - } else if (functionId.getFunctionName().endsWith("fx_getCurrentTime")) { - // Gets the current time - exec_getCurrentTime(returnValue); - } else if (functionId.getFunctionName().endsWith("fx_getCurrentTimeMark")) { - // Gets the tenths of a second in the current or next hour in units of 1/10th second from UTC time - exec_getCurrentTimeMark(returnValue); - } else if (functionId.getFunctionName().endsWith("fx_getMinuteOfTheYear")) { - // Gets the the minutes of current UTC year - exec_getMinuteOfTheYear(returnValue); - } else if (functionId.getFunctionName().endsWith("fx_getDSecond")) { - // Gets the milliseconds point in the current UTC minute - exec_getDSecond(returnValue); - } else if (functionId.getFunctionName().endsWith("xf_parseIpv6Address")) { - exec_parseIpv6Address(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_hashWithSha256") && (parameterList.size() == 1)) { - exec_hashWithSha256(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_signWithEcdsaNistp256WithSha256") && (parameterList.size() == 2)) { - exec_signWithEcdsaNistp256WithSha256(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_verifyWithEcdsaNistp256WithSha256") && (parameterList.size() == 4)) { - exec_verifyWithEcdsaNistp256WithSha256(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_generateKeyPair") && (parameterList.size() == 3)) { - exec_generateKeyPair(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_dms2dd") && (parameterList.size() == 4)) { - exec_dms2dd(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isValidPolygonalRegion") && (parameterList.size() == 1)) { - exec_isValidPolygonalRegion(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isPolygonalRegionInside") && (parameterList.size() == 2)) { - exec_isPolygonalRegionInside(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isLocationInsideCircularRegion") && (parameterList.size() == 2)) { - exec_isLocationInsideCircularRegion(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isLocationInsideRectangularRegion") && (parameterList.size() == 2)) { - exec_isLocationInsideRectangularRegion(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isLocationInsidePolygonalRegion") && (parameterList.size() == 2)) { - exec_isLocationInsidePolygonalRegion(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_isLocationInsideIdentifiedRegion") && (parameterList.size() == 2)) { - exec_isLocationInsideIdentifiedRegion(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_loadCertificates") && (parameterList.size() == 2)) { - exec_loadCertificates(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_unloadCertificates") && (parameterList.size() == 0)) { - exec_unloadCertificates(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_readCertificate") && (parameterList.size() == 2)) { - exec_readCertificate(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_readCertificateDigest") && (parameterList.size() == 2)) { - exec_readCertificateDigest(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_readSigningKey") && (parameterList.size() == 2)) { - exec_readSigningKey(parameterList, returnValue); - } else if (functionId.getFunctionName().endsWith("fx_readEncryptingKey") && (parameterList.size() == 2)) { - exec_readEncryptingKey(parameterList, returnValue); - } else { - _logger.severe("Unprocessed external function"); - result = m_triKO; - } - //TERFactory.getInstance().logDebug("<<< PluginAdapter.triExternalFunction: " + ByteHelper.byteArrayToString(returnValue.getEncodedParameter())); - return result; - } - - public void onConnectionClosed() { - _logger.entering("PluginAdapter", "onConnectionClosed"); - synchronized(this) { - notify(); - } - } - - public void onConnectionEstablished() { - _logger.entering("PluginAdapter", "onConnectionEstablished"); - } - - public void onError(String error) { - _logger.entering("PluginAdapter", "onError", error); - } - - @Override - public TriStatus triPAReset() { -// TERFactory.getInstance().logDebug("triPAReset"); - return m_triOK; - } - - @Override - public TriStatus triReadTimer(TriTimerId timerId, TriTimerDuration elapsedTime) { - throw new RuntimeException(); - } - - @Override - public TriStatus triStartTimer(TriTimerId timerId, TriTimerDuration timerDuration) { - throw new RuntimeException(); - } - - @Override - public TriStatus triStopTimer(TriTimerId timerId) { - throw new RuntimeException(); - } - - @Override - public TriStatus triTimerRunning(TriTimerId timerId, TriBoolean running) { - throw new RuntimeException(); - } - - @Override - public void triEnqueueCall(TriPortId tsiPortId, TriAddress SUTaddress, TriComponentId componentId, TriSignatureId signatureId, TriParameterList parameterList) { - throw new RuntimeException(); - } - - @Override - public void triEnqueueException(TriPortId tsiPortId, TriAddress sutAddress, TriComponentId componentId, TriSignatureId signatureId, - TriException exception) { - throw new RuntimeException(); - } - - @Override - public void triEnqueueMsg(TriPortId tsiPortId, TriAddress sutAddress, TriComponentId componentId, TriMessage receivedMessage) { - TriProvider.getInstance().getTriCommunicationTE().triEnqueueMsg( - tsiPortId, - null, - componentId, - receivedMessage); - } - - @Override - public void triEnqueueReply(TriPortId tsiPortId, TriAddress address, TriComponentId componentId, TriSignatureId signatureId, TriParameterList parameterList, TriParameter returnValue) { - throw new RuntimeException(); - } - - @Override - public TriStatus triMapParam(TriPortId arg0, TriPortId arg1, TriParameterList arg2) { - throw new RuntimeException(); - } - - @Override - public TriStatus triUnmapParam(TriPortId arg0, TriPortId arg1, TriParameterList arg2) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriCall(TriComponentId arg0, TriPortId arg1, Value arg2, TriSignatureId arg3, TciParameterList arg4) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriCallBC(TriComponentId arg0, TriPortId arg1, TriSignatureId arg2, TciParameterList arg3) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriCallMC(TriComponentId arg0, TriPortId arg1, TciValueList arg2, TriSignatureId arg3, TciParameterList arg4) { - throw new RuntimeException(); - } - - @Override - public Value xtriConvert(Object arg0, org.etsi.ttcn.tci.Type arg1) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriMapParam(TriPortId arg0, TriPortId arg1, TciParameterList arg2) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriRaise(TriComponentId arg0, TriPortId arg1, Value arg2, TriSignatureId arg3, Value arg4) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriRaiseBC(TriComponentId arg0, TriPortId arg1, TriSignatureId arg2, Value arg3) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriRaiseMC(TriComponentId arg0, TriPortId arg1, TciValueList arg2, TriSignatureId arg3, Value arg4) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriReply(TriComponentId arg0, TriPortId arg1, Value arg2, TriSignatureId arg3, TciParameterList arg4, Value arg5) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriReplyBC(TriComponentId arg0, TriPortId arg1, TriSignatureId arg2, TciParameterList arg3, Value arg4) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriReplyMC(TriComponentId arg0, TriPortId arg1, TciValueList arg2, TriSignatureId arg3, TciParameterList arg4, Value arg5) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriSend(TriComponentId compPortId, TriPortId tsiPortId, Value arg2, Value arg3) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriSendBC(TriComponentId arg0, TriPortId arg1, Value arg2) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriSendMC(TriComponentId arg0, TriPortId arg1, TciValueList arg2, Value arg3) { - throw new RuntimeException(); - } - - @Override - public TriStatus xtriUnmapParam(TriPortId arg0, TriPortId arg1, TciParameterList arg2) { - throw new RuntimeException(); - } - - @Override - public TriStatus triStaticMap(TriPortId arg0, TriPortId arg1) { - throw new RuntimeException(); - } - - private void exec_computeIPv6CheckSum(TriParameterList parameterList, TriParameter returnValue) { - _logger.entering("PluginAdapter", "exec_computeIPv6CheckSum"); - - // Source address (128 bits) - byte[] value = parameterList.get(0).getEncodedParameter(); - OctetstringValue sourceAddress = (OctetstringValue)TciProvider.getInstance().getTciCDRequired().getOctetstring().newInstance(); - sourceAddress.setLength(value.length); - for (int i = 0; i < value.length; i++) { - sourceAddress.setOctet(i, value[i]); - } - // Destination address (128 bits) - _logger.info(String.format("Setting parameter %s", parameterList.get(1).getParameterName())); - value = parameterList.get(1).getEncodedParameter(); - OctetstringValue destinationAddress = (OctetstringValue)TciProvider.getInstance().getTciCDRequired().getOctetstring().newInstance(); - destinationAddress.setLength(value.length); - for (int i = 0; i < value.length; i++) { - destinationAddress.setOctet(i, value[i]); - } - // Upper-Layer Packet Length (32 bits) - _logger.info(String.format("Setting parameter %s", parameterList.get(2).getParameterName())); - value = parameterList.get(2).getEncodedParameter(); - IntegerValue payloadLength = (IntegerValue)TciProvider.getInstance().getTciCDRequired().getInteger().newInstance(); - payloadLength.setInteger(ByteHelper.byteArrayToInt(value)); - // Upper-Layer payload - _logger.info(String.format("Setting parameter %s", parameterList.get(3).getParameterName())); - value = parameterList.get(3).getEncodedParameter(); - OctetstringValue payload = (OctetstringValue)TciProvider.getInstance().getTciCDRequired().getOctetstring().newInstance(); - payload.setLength(value.length); - for (int i = 0; i < value.length; i++) { - payload.setOctet(i, value[i]); - } - // Next header value (e.g. 0x3a for ICMPv6) (8bits) - _logger.info(String.format("Setting parameter %s", parameterList.get(4).getParameterName())); - value = parameterList.get(4).getEncodedParameter(); - IntegerValue nextHdr = (IntegerValue)TciProvider.getInstance().getTciCDRequired().getInteger().newInstance(); - nextHdr.setInteger(ByteHelper.byteArrayToInt(value)); - // Execute the function - OctetstringValue checksum = _extfuncsImpl.fx_computeIPv6CheckSum( - sourceAddress, - destinationAddress, - payloadLength, - payload, - nextHdr - ); - _logger.info(String.format("fx_computeIPv6CheckSum returns 0x%02x%02x", checksum.getOctet(0), checksum.getOctet(1))); - value = new byte[checksum.getLength()]; - for (int i = 0; i < value.length; i++) { - value[i] = (byte)checksum.getOctet(i); - } - returnValue.setParameterPassingMode(TriParameterPassingMode.TRI_OUT); - returnValue.setNumberOfBits(value.length * Byte.SIZE); - returnValue.setEncodedParameter(value); - - _logger.exiting("PluginAdapter", "exec_computeIPv6CheckSum", ByteHelper.byteArrayToString(returnValue.getEncodedParameter())); - } // End of method exec_computeIPv6CheckSum - - private void exec_computeDistance(TriParameterList parameterList, TriParameter returnValue) { - _logger.entering("PluginAdapter", "exec_computeDistance"); - -// _logger.info(String.format("Setting parameter %s: %s", parameterList.get(0).getParameterName(), ByteHelper.byteArrayToString(parameterList.get(0).getEncodedParameter()))); - byte[] value = parameterList.get(0).getEncodedParameter(); - IntegerValue latitudeA = (IntegerValue)TciProvider.getInstance().getTciCDRequired().getInteger().newInstance(); - latitudeA.setInteger(ByteHelper.byteArrayToInt(value)); - -// _logger.info(String.format("Setting parameter %s: %s", parameterList.get(1).getParameterName(), ByteHelper.byteArrayToString(parameterList.get(1).getEncodedParameter()))); - value = parameterList.get(1).getEncodedParameter(); - IntegerValue longitudeA = (IntegerValue)TciProvider.getInstance().getTciCDRequired().getInteger().newInstance(); - longitudeA.setInteger(ByteHelper.byteArrayToInt(value)); - -// _logger.info(String.format("Setting parameter %s: %s", parameterList.get(2).getParameterName(), ByteHelper.byteArrayToString(parameterList.get(2).getEncodedParameter()))); - value = parameterList.get(2).getEncodedParameter(); - IntegerValue latitudeB = (IntegerValue)TciProvider.getInstance().getTciCDRequired().getInteger().newInstance(); - latitudeB.setInteger(ByteHelper.byteArrayToInt(value)); - -// _logger.info(String.format("Setting parameter %s: %s", parameterList.get(3).getParameterName(), ByteHelper.byteArrayToString(parameterList.get(3).getEncodedParameter()))); -